repo
string
commit
string
message
string
diff
string
danieljfarrell/website-2.0
404748a18b81b253fa509b41352d60753960943e
Added lightbox effect.
diff --git a/blueprint/.DS_Store b/blueprint/.DS_Store index 9c953a1..34cc118 100644 Binary files a/blueprint/.DS_Store and b/blueprint/.DS_Store differ diff --git a/blueprint/plugins/lightbox.css b/blueprint/plugins/lightbox.css new file mode 100755 index 0000000..3b5f7aa --- /dev/null +++ b/blueprint/plugins/lightbox.css @@ -0,0 +1,27 @@ +#lightbox{ position: absolute; left: 0; width: 100%; z-index: 100; text-align: center; line-height: 0;} +#lightbox img{ width: auto; height: auto;} +#lightbox a img{ border: none; } + +#outerImageContainer{ position: relative; background-color: #fff; width: 250px; height: 250px; margin: 0 auto; } +#imageContainer{ padding: 10px; } + +#loading{ position: absolute; top: 40%; left: 0%; height: 25%; width: 100%; text-align: center; line-height: 0; } +#hoverNav{ position: absolute; top: 0; left: 0; height: 100%; width: 100%; z-index: 10; } +#imageContainer>#hoverNav{ left: 0;} +#hoverNav a{ outline: none;} + +#prevLink, #nextLink{ width: 49%; height: 100%; background-image: url(data:image/gif;base64,AAAA); /* Trick IE into showing hover */ display: block; } +#prevLink { left: 0; float: left;} +#nextLink { right: 0; float: right;} +#prevLink:hover, #prevLink:visited:hover { background: url(../images/prevlabel.gif) left 15% no-repeat; } +#nextLink:hover, #nextLink:visited:hover { background: url(../images/nextlabel.gif) right 15% no-repeat; } + +#imageDataContainer{ font: 10px Verdana, Helvetica, sans-serif; background-color: #fff; margin: 0 auto; line-height: 1.4em; overflow: auto; width: 100% ; } + +#imageData{ padding:0 10px; color: #666; } +#imageData #imageDetails{ width: 70%; float: left; text-align: left; } +#imageData #caption{ font-weight: bold; } +#imageData #numberDisplay{ display: block; clear: left; padding-bottom: 1.0em; } +#imageData #bottomNavClose{ width: 66px; float: right; padding-bottom: 0.7em; outline: none;} + +#overlay{ position: absolute; top: 0; left: 0; z-index: 90; width: 100%; height: 500px; background-color: #000; } diff --git a/freebies/pvtrace/index.html b/freebies/pvtrace/index.html index 77514df..dd95e8d 100644 --- a/freebies/pvtrace/index.html +++ b/freebies/pvtrace/index.html @@ -1,116 +1,122 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London" /> <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated" /> <meta name="author" content="Daniel J Farrell" /> <title>Daniel J Farrell</title> <!-- Framework CSS --> <link rel="stylesheet" href="../../blueprint/screen.css" type="text/css" media="screen, projection"> <link rel="stylesheet" href="../../blueprint/print.css" type="text/css" media="print"> <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> <!-- Import fancy-type plugin --> <link rel="stylesheet" href="../../blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> <link rel="stylesheet" href="../../blueprint/plugins/navigation/sliding.css" type="text/css" media="screen, projection" /> - + + <!-- Lightbox --> + <script type="text/javascript" src="js/prototype.js"></script> + <script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script> + <script type="text/javascript" src="js/lightbox.js"></script> + <link rel="stylesheet" href="../../blueprint/plugins/lightbox.css" type="text/css" media="screen" /> + </head> <body> <hr class="space"> <div class="container"> <div class="span-21 header"> <div class="span-6"> <h1 class="light">Daniel J Farrell</h1> </div> <div class="push-1 span-13"> <ul class="green"> <li class="green"><a href="../../" title="home" ><span>home</span></a></li> <li class="green"><a href="../../research/" title="research"><span>research</span></a></li> <li class="green"><a href="../" title="freebies" class="current"><span>freebies</span></a></li> <li class="green" ><a href="../../contact/" title="contact"><span>contact</span></a></li> </ul> </div> </div> <hr class="space"> <!-- Body --> <div class="span-12 colborder"> <h3>PVTrace</h3> <h3 class="alt">Optical monte-carlo simulation of luminescent photovoltaic devices</h3> <p>PVTrace builds on over 3 years of research and development of Monte-Carlo simulation codes at Imperial College. It is the latest version of my luminescent concentrator simulation software and brings together some advanced concepts including:</p> <ul> <li><a href="http://en.wikipedia.org/wiki/Constructive_solid_geometry">Constructive Solid Geometry</a></li> <li>Generalised 3D ray intersections (ray optics): <ul> <li>ray-box</li> <li>ray-cylinder</li> <li>ray-CSG object</li> </ul></li> <li>Arbitrary 3D object transformations: <ul> <li>translation</li> <li>rotation</li> <li>scaling and skewing</li> </ul></li> <li>Photon path visualiser</li> <li>Statistical collection of photonic properties: <ul> <li>wavelength</li> <li>direction</li> <li>polarisation (no appear soon)</li> </ul></li> <li>Fresnel reflection and refraction</li> <li>Sampling from overlapping statistical distributions.</li> </ul> <p>The complex solid geometry feature means that we are no limited to simulation of primitive shapes. Any shape that can be made using a union, difference or intersection operation can be made. In principle any shape can be simulated.</p> <p>PVTrace is entirely written in Python. Using the <a href="http://numpy.scipy.org">numpy</a> and <a href="http://www.scipy.org">scipy</a> libraries. The philosophy here is to use a programming language that allows for rapid development rather than speed of execution. On a single core machine PVTrace only takes a few minutes to produce sensible results which for me is an acceptable trade-off considering the pleasure it is to write and debug in Python!</p> </div> <!-- Column --> <div class="span-6 last"> <div class="success"> <strong>PVTrace</strong> is become open-source for the benefit of the PV community! PVTrace can be licensed for commercial work or consulting projects. Become a developer soon... </div> <hr class="space"> <hr class="space"> <div> - <a href="pvtrace.jpg"><img src="pvtrace.jpg" width="230" class="push-0 shadow" alt="pvtrace: optical monte-carlo simulation of luminescent photovoltaic devices."></a><p class="pcaption">Screenshot of pvtrace running.</p> + <a href="pvtrace.jpg" rel="lightbox" title="PVTrace: Optical monte-carlo simulation of luminescent photovoltaic devices"><img src="pvtrace.jpg" width="230" class="push-0 shadow" alt="pvtrace: optical monte-carlo simulation of luminescent photovoltaic devices."></a><p class="pcaption">Screenshot of pvtrace running.</p> </div> <hr class="space"> <hr class="space"> <div> <img src="http://upload.wikimedia.org/wikipedia/commons/8/8b/Csg_tree.png" width="240" class="push-0 shadow" alt="Constructive solid geometry. "><p class="pcaption">Constructive solid geometry operations.</p> </div> </div> </div> </body> </html>
danieljfarrell/website-2.0
c7d449798895115a9567dfd1eed9e10ed7d54a11
Version initially published on 11 August 2010.
diff --git a/contact/index.html b/contact/index.html index b217461..94c6dec 100644 --- a/contact/index.html +++ b/contact/index.html @@ -1,95 +1,90 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" - "http://www.w3.org/TR/html4/strict.dtd"> - +"http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> -<head> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> - <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London" /> - <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated" /> - <meta name="author" content="Daniel J Farrell" /> - <title>Daniel J Farrell</title> - - <!-- Framework CSS --> - <link rel="stylesheet" href="../blueprint/screen.css" type="text/css" media="screen, projection"> - <link rel="stylesheet" href="../blueprint/print.css" type="text/css" media="print"> - <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> - <!-- Import fancy-type plugin --> - <link rel="stylesheet" href="../blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> - <link rel="stylesheet" href="../blueprint/plugins/navigation/sliding.css" type="text/css" media="screen, projection" /> - -</head> - -<body> - - <hr class="space"> - - - <div class="container"> - - - <div class="span-6"> - <h1 class="light">Daniel J Farrell</h1> - </div> - - <div class="push-1 span-13"> - - <ul class="green"> - <li class="green"><a href="../index.html" title="home" ><span>home</span></a></li> - <li class="green"><a href="../research/index.html" title="research" ><span>research</span></a></li> - <li class="green"><a href="../freebies/index.html" title="freebies"><span>freebies</span></a></li> - <li class="green" ><a href="index.html" title="contact" class="current"><span>contact</span></a></li> - </ul> - </div> - - <hr class="space"> - - <div class="span-6"> - <h6>At Imperial College London</h6> + <head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London"> + <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated"> + <meta name="author" content="Daniel J Farrell"> + <title> + Daniel J Farrell + </title><!-- Framework CSS --> + <link rel="stylesheet" href="../blueprint/screen.css" type="text/css" media="screen, projection"> + <link rel="stylesheet" href="../blueprint/print.css" type="text/css" media="print"><!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> + <!-- Import fancy-type plugin --> + <link rel="stylesheet" href="../blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> + <link rel="stylesheet" href="../blueprint/plugins/navigation/sliding.css" type="text/css" media="screen, projection"> + </head> + <body> <hr class="space"> - <a href="http://maps.google.co.uk/maps/place?cid=17449252295702573143&q=imperial+college+london+physics+department&hl=en&gl=uk"><img src="ic.jpg" alt="Location of Imperial College Department of Physics" width="260"></a> - </div> - <div class="span-6 push-2"> - - <h6>On the web</h6> - <hr class="space"> - <a href="http://twitter.com/danieljfarrell"> <img src="../img/twitter.jpg" width="35"/></a> - <a href="http://linkedin.com/in/danieljfarrell"> <img src="../img/linkedin.jpg" width="33"/></a> - <a href="http://www.mendeley.com/profiles/daniel-farrell/"><img border="0" src="http://www.mendeley.com/embed/icon/1/blue/small" - </div> - - - <div class="span-3 push-1"> - - <h6>On Skype</h6> - <hr class="space"> - <!-- + <div class="container"> + <div class="span-6"> + <h1 class="light"> + Daniel J Farrell + </h1> + </div> + <div class="push-1 span-13"> + <ul class="green"> + <li class="green"> + <a href="../../" title="home"><span>home</span></a> + </li> + <li class="green"> + <a href="../../research/" title="research"><span>research</span></a> + </li> + <li class="green"> + <a href="../../freebies/" title="freebies"><span>freebies</span></a> + </li> + <li class="green"> + <a href="#" title="contact" class="current" ><span>contact</span></a> + </li> + </ul> + </div> + <hr class="space"> + <div class="span-13 colborder"> + <div class="span-6 "> + <h6> + Imperial College London &mdash; <a href="http://www.imperial.ac.uk/qpv">Quantum Photovoltaics Group</a> + </h6> + <hr class="space"> + <a href="http://maps.google.co.uk/maps/place?cid=17449252295702573143&amp;q=imperial+college+london+physics+department&amp;hl=en&amp;gl=uk"><img src="ic.jpg" alt="Location of Imperial College Department of Physics" width="200"></a> + <hr class="space"> + <p> + Dr. Daniel J Farrell<br> + Experimental Solid State Physics<br> + Blackett Laboratory,<br> + Imperial College London,<br> + Prince Consort Road,<br> + London SW7 2AZ.<br> + U.K.<br> + e-mail: <a href="mailto:[email protected]">[email protected]</a><br> + tel: (+44) - (0)20 7594 7305 + </p> + </div> + + <div class="span-3 push-2 "> + <h6> + On Skype + </h6> + <hr class="space"> + <!-- Skype 'My status' button http://www.skype.com/go/skypebuttons --> -<script type="text/javascript" src="http://download.skype.com/share/skypebuttons/js/skypeCheck.js"></script> -<a href="skype:daniel.james.farrell?call"><img src="http://mystatus.skype.com/balloon/daniel%2Ejames.farrell" style="border: none;" width="150" height="60" alt="My status" /></a> - </div> - - <hr class="space"> - <hr class="space"> - - <div class="span-4"> - - <p>Dr. Daniel J Farrell<br> - Experimental Solid State Physics<br> - Blackett Laboratory,<br> - Imperial College London,<br> - Prince Consort Road,<br> - London SW7 2AZ.<br> - U.K. <br> - e-mail: <a href="mailto:[email protected]">[email protected]</a><br> - tel: (+44) - (0)20 7594 7305 - </p> - </div> - + <script type="text/javascript" src="http://download.skype.com/share/skypebuttons/js/skypeCheck.js"> +</script> <a href="skype:daniel.james.farrell?call"><img src="http://mystatus.skype.com/balloon/daniel%2Ejames.farrell" style="border: none;" width="150" height="60" alt="My status"></a> + </div> + + </div> + <div class="span-6 last"> + + <div> + <h3><span class="alt">Follow me here...</span></h3> + <a href="http://twitter.com/danieljfarrell"> <img src="../img/twitter.jpg" width="35"/></a> + <a href="http://linkedin.com/in/danieljfarrell"> <img src="../img/linkedin.jpg" width="33"/></a> + <a href="http://www.mendeley.com/profiles/daniel-farrell/"><img border="0" src="http://www.mendeley.com/embed/icon/1/blue/small" alt="Daniel Farrell's bibliography"/></a> + </div> + </div> </div> - </div> - -</body> + </body> </html> diff --git a/freebies/DAQ.png b/freebies/DAQ.png new file mode 100644 index 0000000..d04a770 Binary files /dev/null and b/freebies/DAQ.png differ diff --git a/freebies/index.html b/freebies/index.html index 5040ff5..d15583b 100644 --- a/freebies/index.html +++ b/freebies/index.html @@ -1,79 +1,113 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" - "http://www.w3.org/TR/html4/strict.dtd"> - +"http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> -<head> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> - <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London" /> - <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated" /> - <meta name="author" content="Daniel J Farrell" /> - <title>Daniel J Farrell</title> - - <!-- Framework CSS --> - <link rel="stylesheet" href="../blueprint/screen.css" type="text/css" media="screen, projection"> - <link rel="stylesheet" href="../blueprint/print.css" type="text/css" media="print"> - <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> - <!-- Import fancy-type plugin --> - <link rel="stylesheet" href="../blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> - <link rel="stylesheet" href="../blueprint/plugins/navigation/sliding.css" type="text/css" media="screen, projection" /> - -</head> - -<body> - + <head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London"> + <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated"> + <meta name="author" content="Daniel J Farrell"> + <title> + Daniel J Farrell + </title><!-- Framework CSS --> + <link rel="stylesheet" href="../blueprint/screen.css" type="text/css" media="screen, projection"> + <link rel="stylesheet" href="../blueprint/print.css" type="text/css" media="print"><!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> + <!-- Import fancy-type plugin --> + <link rel="stylesheet" href="../blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> + <link rel="stylesheet" href="../blueprint/plugins/navigation/sliding.css" type="text/css" media="screen, projection"> + </head> + <body> <hr class="space"> - - <div class="container"> - - <div class="span-21 header"> - - <div class="span-6"> - <h1 class="light">Daniel J Farrell</h1> - </div> - - <div class="push-1 span-13"> - <ul class="green"> - <li class="green"><a href="../index.html" title="home" ><span>home</span></a></li> - <li class="green"><a href="../research/index.html" title="research"><span>research</span></a></li> - <li class="green"><a href="index.html" title="freebies" class="current"><span>freebies</span></a></li> - <li class="green" ><a href="../contact/index.html" title="contact"><span>contact</span></a></li> - </ul> + <div class="container"> + <div class="span-21 header"> + <div class="span-6"> + <h1 class="light"> + Daniel J Farrell + </h1> + </div> + <div class="push-1 span-13"> + <ul class="green"> + <li class="green"> + <a href="../" title="home"><span>home</span></a> + </li> + <li class="green"> + <a href="../research/" title="research"><span>research</span></a> + </li> + <li class="green"> + <a href="#" title="freebies" class="current"><span>freebies</span></a> + </li> + <li class="green"> + <a href="../contact/" title="contact"><span>contact</span></a> + </li> + </ul> + </div> </div> - - </div> - - <hr class="space"> - - <!-- Body --> - <div class="span-21 "> - - <h3>Freebies &mdash; everyone likes freebies! </h3> - - - <p>A collection of interesting things related to photovoltaics and my research.</p> - <hr class="space"> - <div class="span-6"> - <a href="pvtrace/index.html"><img src="pvtrace/pvtrace.jpg" width="230" class="push-0 shadow" alt="pvtrace: optical monte-carlo simulation of luminescent photovoltaic devices."></a><p class="pcaption">PVTrace: Optical monte-carlo simulation of luminescent photovoltaic devices</p> - <hr class="space"> - <p><strong>PVTrace</strong> is become open-source for the benefit of the PV community! PVTrace can be licensed for commercial work or consulting projects. Become a developer soon...</p> - </div> - - <div class="span-6 push-1"> - <a href="quantumofsol/index.html"><img src="qos.png" width="230" class="push-0 shadow" alt="Quantum of Sol: the next generation of solar cells in a WebApp."></a><p class="pcaption">Quantum of Sol: Now a Webapp!</p> - <hr class="space"> - <hr class="space"> - <p><strong>Quantum of Sol</strong> was our highly successful outreach adventure at prestigious <a href="http://royalsociety.org/quantum-of-sol---the-next-generation-of-solar-cells/">Royal Summer Science Exhibition 2009</a>. First year summer project students Matthias Kraft and Aidan Taylor joined the research group to make a webapp that describes the losses in a Shockley-Queisser solar and how they can be overcome by moving to advanced PV concepts such at hot-carriers.</p> - + <!-- Body --> + <div class="span-13 colborder"> + <h3> + Freebies — everyone likes freebies! + </h3> + <p> + A collection of interesting things related to photovoltaics and my research. + </p> + <hr class="space"> + + <h5>PVTrace</h5> + <div class="span-6"> + + <a href="pvtrace/"><img src="pvtrace/pvtrace.jpg" width="200" class="push-0 " alt="pvtrace: optical monte-carlo simulation of luminescent photovoltaic devices."></a> + <p class="pcaption"> + PVTrace: Optical monte-carlo simulation of luminescent photovoltaic devices + </p> + </div> + <p> + <strong>PVTrace</strong> will soon become open-source software for academic use. PVTrace can be licensed for commercial applications or I can be hired for consulting projects. Interested in knowing more, <a href="../contact/"> get in contact</a>. + </p> + + <hr class=""> + + <h5>Quantum of Sol</h5> + + <div class="span-6"> + <a href="quantumofsol/"><img src="qos.png" width="200" class="push-0 " alt="Quantum of Sol: the next generation of solar cells in a WebApp."></a> + <p class="pcaption"> + Quantum of Sol: Now a Webapp! + </p> + </div> + <p> + <strong>Quantum of Sol</strong> was our highly successful outreach adventure at the prestigious <a href="http://royalsociety.org/quantum-of-sol---the-next-generation-of-solar-cells/">Royal Summer Science Exhibition 2009</a>. Imperial College Physic students Matthias Kraft and Aidan Taylor joined me for their summer research project 2010 and made a <a href="quantumofsol/">Web app</a> to explained solar energy conversion. Their work illustrates the current/voltage trade off with conversional solar cells, and highlights how this can be circumvented by using the hot-carrier approach. + </p> + + <hr class=""> + + + <h5>pydaq</h5> + + <div class="span-5 append-1"> + <img src="DAQ.png" width="200" class="push-0" alt="Python software to control the analogue ports of National instruments DAQ 6008."> + <p class="pcaption"> + Python control of USB NI-DAQ. + </p> + </div> + <p> + <strong>National instruments</strong> make a very versatile USB Data Acquisition (DAQ) box. Let's face it, using the NI C API and programming on Windows are not the most inspiring tasks. I wrote a small python class that makes using this DAQ on Windows a bit more fun! You can find the pydaq project <a href="http://github.com/danieljfarrell/pydaq"> here on github.com</a>. It makes it simple to access the current and voltage values on any of the port: + + <div class="span-6"> + <script src="http://gist.github.com/518737.js?file=gistfile1.py"></script> + </div> + </p> + + </div> - - + <div> + <h3><span class="alt">Follow me here...</span></h3> + <a href="http://twitter.com/danieljfarrell"> <img src="../img/twitter.jpg" width="35"/></a> + <a href="http://linkedin.com/in/danieljfarrell"> <img src="../img/linkedin.jpg" width="33"/></a> + <a href="http://www.mendeley.com/profiles/daniel-farrell/"><img border="0" src="http://www.mendeley.com/embed/icon/1/blue/small" alt="Daniel Farrell's bibliography"/></a> + </div> + </div> - - - </div> - -</body> + </body> </html> diff --git a/freebies/pvtrace/index.html b/freebies/pvtrace/index.html index 8e315d4..77514df 100644 --- a/freebies/pvtrace/index.html +++ b/freebies/pvtrace/index.html @@ -1,116 +1,116 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London" /> <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated" /> <meta name="author" content="Daniel J Farrell" /> <title>Daniel J Farrell</title> <!-- Framework CSS --> <link rel="stylesheet" href="../../blueprint/screen.css" type="text/css" media="screen, projection"> <link rel="stylesheet" href="../../blueprint/print.css" type="text/css" media="print"> <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> <!-- Import fancy-type plugin --> <link rel="stylesheet" href="../../blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> <link rel="stylesheet" href="../../blueprint/plugins/navigation/sliding.css" type="text/css" media="screen, projection" /> </head> <body> <hr class="space"> <div class="container"> <div class="span-21 header"> <div class="span-6"> <h1 class="light">Daniel J Farrell</h1> </div> <div class="push-1 span-13"> <ul class="green"> - <li class="green"><a href="../../index.html" title="home" ><span>home</span></a></li> - <li class="green"><a href="../../research/index.html" title="research"><span>research</span></a></li> - <li class="green"><a href="../index.html" title="freebies" class="current"><span>freebies</span></a></li> - <li class="green" ><a href="../../contact/index.html" title="contact"><span>contact</span></a></li> + <li class="green"><a href="../../" title="home" ><span>home</span></a></li> + <li class="green"><a href="../../research/" title="research"><span>research</span></a></li> + <li class="green"><a href="../" title="freebies" class="current"><span>freebies</span></a></li> + <li class="green" ><a href="../../contact/" title="contact"><span>contact</span></a></li> </ul> </div> </div> <hr class="space"> <!-- Body --> <div class="span-12 colborder"> <h3>PVTrace</h3> <h3 class="alt">Optical monte-carlo simulation of luminescent photovoltaic devices</h3> <p>PVTrace builds on over 3 years of research and development of Monte-Carlo simulation codes at Imperial College. It is the latest version of my luminescent concentrator simulation software and brings together some advanced concepts including:</p> <ul> <li><a href="http://en.wikipedia.org/wiki/Constructive_solid_geometry">Constructive Solid Geometry</a></li> <li>Generalised 3D ray intersections (ray optics): <ul> <li>ray-box</li> <li>ray-cylinder</li> <li>ray-CSG object</li> </ul></li> <li>Arbitrary 3D object transformations: <ul> <li>translation</li> <li>rotation</li> <li>scaling and skewing</li> </ul></li> <li>Photon path visualiser</li> <li>Statistical collection of photonic properties: <ul> <li>wavelength</li> <li>direction</li> <li>polarisation (no appear soon)</li> </ul></li> <li>Fresnel reflection and refraction</li> <li>Sampling from overlapping statistical distributions.</li> </ul> <p>The complex solid geometry feature means that we are no limited to simulation of primitive shapes. Any shape that can be made using a union, difference or intersection operation can be made. In principle any shape can be simulated.</p> <p>PVTrace is entirely written in Python. Using the <a href="http://numpy.scipy.org">numpy</a> and <a href="http://www.scipy.org">scipy</a> libraries. The philosophy here is to use a programming language that allows for rapid development rather than speed of execution. On a single core machine PVTrace only takes a few minutes to produce sensible results which for me is an acceptable trade-off considering the pleasure it is to write and debug in Python!</p> </div> <!-- Column --> <div class="span-6 last"> <div class="success"> <strong>PVTrace</strong> is become open-source for the benefit of the PV community! PVTrace can be licensed for commercial work or consulting projects. Become a developer soon... </div> <hr class="space"> <hr class="space"> <div> <a href="pvtrace.jpg"><img src="pvtrace.jpg" width="230" class="push-0 shadow" alt="pvtrace: optical monte-carlo simulation of luminescent photovoltaic devices."></a><p class="pcaption">Screenshot of pvtrace running.</p> </div> <hr class="space"> <hr class="space"> <div> <img src="http://upload.wikimedia.org/wikipedia/commons/8/8b/Csg_tree.png" width="240" class="push-0 shadow" alt="Constructive solid geometry. "><p class="pcaption">Constructive solid geometry operations.</p> </div> </div> </div> </body> </html> diff --git a/freebies/quantumofsol/Info.plist b/freebies/quantumofsol/Info.plist index a538adc..fa60933 100755 --- a/freebies/quantumofsol/Info.plist +++ b/freebies/quantumofsol/Info.plist @@ -1,12 +1,12 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CPApplicationDelegateClass</key> <string>AppController</string> <key>CPBundleName</key> - <string>NewApplication</string> + <string>Quantum of Sol Webapp</string> <key>CPPrincipalClass</key> <string>CPApplication</string> </dict> </plist> diff --git a/index.html b/index.html index b94b13b..dc93877 100644 --- a/index.html +++ b/index.html @@ -1,92 +1,88 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" - "http://www.w3.org/TR/html4/strict.dtd"> - +"http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> -<head> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> - <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London" /> - <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated" /> - <meta name="author" content="Daniel J Farrell" /> - <meta name="microid" content="mailto+http:sha1:ab095e627455a292fb5fd60550b0fa4a2105ae79" /> - <link rel="openid.server" href="http://openid.claimid.com/server" /> - <link rel="openid.delegate" href="http://daniel.farrell.name" /> - <title>Daniel J Farrell</title> - - <!-- Framework CSS --> - <link rel="stylesheet" href="blueprint/screen.css" type="text/css" media="screen, projection"> - <link rel="stylesheet" href="blueprint/print.css" type="text/css" media="print"> - <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> - <!-- Import fancy-type plugin --> - <link rel="stylesheet" href="blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> - <link rel="stylesheet" href="blueprint/plugins/navigation/sliding.css" type="text/css" media="screen, projection" /> - -</head> - -<body> - + <head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London"> + <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated"> + <meta name="author" content="Daniel J Farrell"> + <meta name="microid" content="mailto+http:sha1:ab095e627455a292fb5fd60550b0fa4a2105ae79"> + <link rel="openid.server" href="http://openid.claimid.com/server"> + <link rel="openid.delegate" href="http://daniel.farrell.name"> + <title> + Daniel J Farrell + </title><!-- Framework CSS --> + <link rel="stylesheet" href="blueprint/screen.css" type="text/css" media="screen, projection"> + <link rel="stylesheet" href="blueprint/print.css" type="text/css" media="print"><!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> + <!-- Import fancy-type plugin --> + <link rel="stylesheet" href="blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> + <link rel="stylesheet" href="blueprint/plugins/navigation/sliding.css" type="text/css" media="screen, projection"> + </head> + <body> <hr class="space"> - <div class="container"> - - - <div class="span-6"> - <h1 class="light">Daniel J Farrell</h1> - </div> - - <div class="push-1 span-13"> - <ul class="green"> - <li class="green"><a href="index.html" title="home" class="current"><span>home</span></a></li> - <li class="green"><a href="research/index.html" title="research"><span>research</span></a></li> - <li class="green"><a href="freebies/index.html" title="freebies"><span>freebies</span></a></li> - <li class="green" ><a href="contact/index.html" title="contact"><span>contact</span></a></li> - </ul> - </div> - - <hr class="space"> - - - <div class="span-12 colborder"> - - <div class="span-6 append-1"> - <img src="img/daniel_j_farrell.jpg" class="top push-0 shadow" alt="test" width="240px"> + <div class="container"> + <div class="span-21 header"> + <div class="span-6"> + <h1 class="light"> + Daniel J Farrell + </h1> + </div> + <div class="push-1 span-13 last"> + <ul class="green"> + <li class="green"> + <a href="#" title="home" class="current"><span>home</span></a> + </li> + <li class="green"> + <a href="research/" title="research"><span>research</span></a> + </li> + <li class="green"> + <a href="freebies/" title="freebies"><span>freebies</span></a> + </li> + <li class="green"> + <a href="contact/" title="contact"><span>contact</span></a> + </li> + </ul> + </div> </div> - - <h6>About</h6> - <p>Daniel is a post doctoral researcher in the Experimental Solid State Physics group at Imperial College London. His research activities include hot-carrier solar cells and spectral modification with luminescent materials.</p> - <hr class="space"> - - <h6>Experience</h6> - <ul> - <li>2009 - present, Research Associate &mdash; Imperial College London. Fabricated, characterised and simulated the first quantum dot based luminescent solar concentrator tandem. Wrote optical Monte-Carlo software: pvtrace.</li> - <li>2004 - 2009, Postgraduate Student &mdash; Imperial College London. Developed a rate model for the hot-carrier solar cell. Performed perturbation theory analysis on cooling in quantum dots.</li> - </ul> + <div class="span-13 colborder"> + <div class="span-6 append-1"> + <img src="img/daniel_j_farrell.jpg" class="top push-0 shadow" alt="test" width="240"> + </div> + <h6> + About + </h6> + <p> + I'm Daniel Farrell, a post doctoral researcher in the Experimental Solid State Physics group at Imperial College London. I research photovoltaic energy conversion, I'm particularly interested in hot-carrier solar cells and spectral modification with luminescent materials. + </p> + <hr class="space"> + <h6> + Experience + </h6> + <ul> + <li>2009 - present, Research Associate — Imperial College London. Fabricated, characterised and simulated the first quantum dot based luminescent solar concentrator tandem. Wrote optical Monte-Carlo software: <a href="freebies/">pvtrace</a>. + </li> + <li>2004 - 2009, Postgraduate Student — Imperial College London. Developed a rate model for the hot-carrier solar cell. Performed perturbation theory analysis on cooling in quantum dots. + </li> + </ul> + </div> + <div> + <h3> + <span class="alt">Follow me here...</span> + </h3><a href="http://twitter.com/danieljfarrell"><img src="img/twitter.jpg" width="35"></a> <a href="http://linkedin.com/in/danieljfarrell"><img src="img/linkedin.jpg" width="33"></a> <a href="http://www.mendeley.com/profiles/daniel-farrell/"><img border="0" src="http://www.mendeley.com/embed/icon/1/blue/small" alt="Daniel Farrell's bibliography"></a> + </div> + <div class="span-13 last"> + <hr> + <h5>Recent publications and talks</h5> + <ul class="publist"> + <li class="pub">D J Farrell and N J Ekins-Daukes, <em>"Photovoltaic technology: Relay dye boosts efficiency"</em>, <strong>Nature Photonics</strong>, 2009, 3: 373 - 374. <a href="http://doi:10.1038/nphoton.2009.108">doi:10.1038/nphoton.2009.108</a> + </li> + <li class="pub">D J Farrell, W G J H M van Sark, S T Velthuijsen and R E I Schropp, R, 2010, <em>"Using amorphous silicon solar cells to boost the viability of luminescent solar concentrators"</em>. <strong>Physica Status Solidi (c)</strong>, 7: 1045–1048. <a href="http://dx.doi.org/10.1002/pssc.200982866">doi:10.1002/pssc.200982866</a> + </li> + <li class="publist">D J Farrell, <em>The next generation of Building Integrated Photovoltaics.</em>", presented to <a class="loud" href="http://www.arup.com">Arup Associates</a>, London 2009. + </li> + </ul> + </div> </div> - - <p> - <h3><span class="alt">Follow me here...</span></h3> - <a href="http://twitter.com/danieljfarrell"> <img src="img/twitter.jpg" width="35"/></a> - <a href="http://linkedin.com/in/danieljfarrell"> <img src="img/linkedin.jpg" width="33"/></a> - <a href="http://www.mendeley.com/profiles/daniel-farrell/"><img border="0" src="http://www.mendeley.com/embed/icon/1/blue/small" alt="Daniel Farrell's bibliography"/></a> - </p> - - - <div class="span-13 last"> - <hr> - <h3 class=""> Recent publications and talks</h3> - <ul class="publist"> - <li class="pub">D J Farrell and N J Ekins-Daukes, <em>"Photovoltaic technology: Relay dye boosts efficiency"</em>, <strong>Nature Photonics</strong>, 2009, 3: 373 - 374. <a href="http://doi:10.1038/nphoton.2009.108">doi:10.1038/nphoton.2009.108 -</a></li> - <li class="pub">D J Farrell, W G J H M van Sark, S T Velthuijsen and R E I Schropp, R, 2010, <em>"Using amorphous silicon solar cells to boost the viability of luminescent solar concentrators"</em>. <strong>Physica Status Solidi (c)</strong>, 7: 1045–1048. <a href="http://dx.doi.org/10.1002/pssc.200982866">doi:10.1002/pssc.200982866</a></li> - - <li class="publist"> - D J Farrell, <em>The next generation of Building Integrated Photovoltaics.</em>", presented to <a class="loud" href="http://www.arup.com">Arup Associates</a>, London 2009. - </li> - </ul> - </div> - - - - </div> - -</body> + </body> </html> diff --git a/research/index.html b/research/index.html index a77e2a2..32271ce 100644 --- a/research/index.html +++ b/research/index.html @@ -1,119 +1,156 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" - "http://www.w3.org/TR/html4/strict.dtd"> - +"http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> -<head> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> - <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London" /> - <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated" /> - <meta name="author" content="Daniel J Farrell" /> - <title>Daniel J Farrell</title> - - <!-- Framework CSS --> - <link rel="stylesheet" href="../blueprint/screen.css" type="text/css" media="screen, projection"> - <link rel="stylesheet" href="../blueprint/print.css" type="text/css" media="print"> - <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> - <!-- Import fancy-type plugin --> - <link rel="stylesheet" href="../blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> - <link rel="stylesheet" href="../blueprint/plugins/navigation/sliding.css" type="text/css" media="screen, projection" /> - -</head> - -<body> - + <head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London"> + <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated"> + <meta name="author" content="Daniel J Farrell"> + <title> + Daniel J Farrell – research + </title><!-- Framework CSS --> + <link rel="stylesheet" href="../blueprint/screen.css" type="text/css" media="screen, projection"> + <link rel="stylesheet" href="../blueprint/print.css" type="text/css" media="print"><!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> + <!-- Import fancy-type plugin --> + <link rel="stylesheet" href="../blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> + <link rel="stylesheet" href="../blueprint/plugins/navigation/sliding.css" type="text/css" media="screen, projection"> + </head> + <body> <hr class="space"> - - <div class="container"> - - <div class="span-21 header"> - - <div class="span-6"> - <h1 class="light">Daniel J Farrell</h1> + <div class="container"> + <div class="span-21 header"> + <div class="span-6"> + <h1 class="light"> + Daniel J Farrell + </h1> + </div> + <div class="push-1 span-13 last"> + <ul class="green"> + <li class="green"> + <a href="../" title="home"><span>home</span></a> + </li> + <li class="green"> + <a href="#" title="research" class="current"><span>research</span></a> + </li> + <li class="green"> + <a href="../freebies/" title="freebies"><span>freebies</span></a> + </li> + <li class="green"> + <a href="../contact/" title="contact"><span>contact</span></a> + </li> + </ul> + </div> </div> - - <div class="push-1 span-13 last "> - - <ul class="green"> - <li class="green"><a href="../index.html" title="home" ><span>home</span></a></li> - <li class="green"><a href="index.html" title="research" class="current"><span>research</span></a></li> - <li class="green"><a href="../freebies/index.html" title="freebies"><span>freebies</span></a></li> - <li class="green" ><a href="../contact/index.html" title="contact"><span>contact</span></a></li> - </ul> - </div> - - </div> - - <hr class="space"> - - - - <div class="span-12 colborder"> - - - <h3>Research interests</h3> - - <div class="success"> - For articles interesting things related photovoltaics see <a href="../freebies/index.html">Freebies</a> page. - </div> - - - <p>Efficiency and cost drive photovoltaic research. During my PhD I worked on a novel optical concentrator with the aim of reducing cost. Then during my postdoc I switched gears an looked at what is ultimately possible in terms of high efficiency. Below I briefly discuss my experience in these areas.</p> - - <h5>Luminescent solar concentrators</h5> - - <p>One purely optical approach to the reduction of costs is the Luminescent Solar Concentrator (LSC). During my PhD I developed the first quantum dot based luminescent concentrator tandem, and have written optical Monte-Carlo simulation software that can model devices with complicated shapes and optical properties.</p> + <hr class="space"> + <div class="span-13 colborder"> + <h3> + Research interests + </h3> + <p> + Efficiency and cost drive photovoltaic research. During my PhD I worked on a novel optical concentrator with the aim of reducing cost. Then during my postdoc I switched gears an looked at what is ultimately possible in terms of high efficiency. Below I briefly discuss my experience in these areas. + </p> + <h5> + Luminescent solar concentrators + </h5> - <p>Cost reduction is achieved by replacing the light harvesting area of conventional solar panels by low-cost, planar luminescent waveguides. A small area of solar cells attached to the edges, therefore reducing the cost of the whole device. </p> + <div class="span-5 success "> + <h6> + Key Contributions + </h6> + <ul> + <li>The first quantum dot based luminescent concentrator tandem + </li> + <li>State of the art optical Monte-Carlo model: <a href="../freebies/">PVTrace</a>. + </li> + </ul> + </div> - <p>What I call ‘first generation’ luminescent concentrators were devised in the late 1970s and offered realistic savings when the cost-per-Watt of flat-plate silicon was ~30$/W. Research into LSCs has continued to the present day; focusing on how new materials such as colloidal nano-structures and photonic structures can augment traditional designs. However, the best of these structures are still only capable of transporting ~10% of incident photons to the cells. In these devices, photon transport towards the cells is severely hindered by multiple reabsorption events that redirect photons out of waveguide modes, and limit devices to low efficiency. </p> + <p> + One purely optical approach to the reduction of costs is the Luminescent Solar Concentrator (LSC). + </p> - <p>Research interests are now focusing on ‘second generation’ approaches, which attempt to enhance the optical transport, and should enable high power conversion efficiency at low cost, provided the optical properties can be pushed to the limit. If this is achieved, the theoretical efficiency limits of luminescent concentrator are the same as for conventional solar cells, ~30%.</p> + <p> + Cost reduction is achieved by replacing the light harvesting area of conventional solar panels by low-cost, planar luminescent waveguides. A small area of solar cells attached to the edges, therefore reducing the cost of the whole device. + </p> + <p> + What I call ‘first generation’ luminescent concentrators were devised in the late 1970s and offered realistic savings when the cost-per-Watt of flat-plate silicon was ~30$/W. Research into LSCs has continued to the present day; focusing on how new materials such as colloidal nano-structures and photonic structures can augment traditional designs. However, the best of these structures are still only capable of transporting ~10% of incident photons to the cells. In these devices, photon transport towards the cells is severely hindered by multiple reabsorption events that redirect photons out of waveguide modes, and limit devices to low efficiency. + </p> + <p> + Research interests are now focusing on ‘second generation’ approaches, which attempt to enhance the optical transport, and should enable high power conversion efficiency at low cost, provided the optical properties can be pushed to the limit. If this is achieved, the theoretical efficiency limits of luminescent concentrators are the same as conventional solar cells, ~30%. + </p> + <h5> + Hot-carrier solar cells + </h5> + + <div class="span-5 success "> + <h6> + Key Contributions + </h6> + <ul> + <li>Rate model for the hot-carrier solar cell + </li> + <li>Perturbation theory analysis of cooling. + </li> + </ul> + </div> - <h5>Hot-carrier solar cell</h5> - - <p>The hot-carrier solar cell is one of the most ambitious attempts at making the ultimate photovoltaic converter. It has the potential to reach 84% power conversion efficiency.</p> - - <p>In this concept, thermalisation losses are eliminated using a mechanism which prevents charge carriers from interacting with the lattice. Energy that would otherwise transfer to the lattice, and lost, is stored in the carrier population as excess heat. In theory this enables very high conversion efficiencies because a low bandgap material can be chosen to maximise absorption across the spectrum, and yet still achieve high voltage per carrier.</p> - - <p>The good voltage performance is achieved using <em>'energy selective contacts'</em> (the 'pipes' that extract the electrons from the conduction band and holes from the valence band in the diagram). These contacts play 2 crucial roles: (1) they prevent the hot-carrier population from being cooled when in contact with the metal electrodes, and (2) the voltage of the solar cell is determined by the energy separation between the electron and hole contact. Thus the hot-carrier solar cell can the best of both worlds: a high current by using a low bandgap absorber, and a high voltage from using energy selective contacts.</p> - - </div> - - <div class="span-6 last"> - <hr class="space"> - <hr class="space"> - <hr class="space"> - <hr class="space"> - <hr class="space"> - <hr class="space"> - <hr class="space"> - <hr class="space"> - <hr class="space"> <p> - <img src="../img/lsc.jpg" width=240 class="top push-0 shadow" alt="Luminescent solar concentrators."> - <div class="pcaption"> - <p>Luminescent solar concentrators.</p></div> + The hot-carrier solar cell is one of the most ambitious attempts at making the ultimate photovoltaic converter. It has the potential to reach 84% power conversion efficiency. + </p> + <p> + In this concept, thermalisation losses are eliminated using a mechanism which prevents charge carriers from interacting with the lattice. Energy that would otherwise transfer to the lattice, and lost, is stored in the carrier population as excess heat. In theory this enables very high conversion efficiencies because a low bandgap material can be chosen to maximise absorption across the spectrum, and yet still achieve high voltage per carrier. + </p> + <p> + The good voltage performance is achieved using <em>'energy selective contacts'</em> (the 'pipes' that extract the electrons from the conduction band and holes from the valence band in the diagram). These contacts play 2 crucial roles: (1) they prevent the hot-carrier population from being cooled when in contact with the metal electrodes, and (2) the voltage of the solar cell is determined by the energy separation between the electron and hole contact. Thus the hot-carrier solar cell can the best of both worlds: a high current by using a low bandgap absorber, and a high voltage from using energy selective contacts. </p> + <p> + To better understand the current/voltage trade off that occurs in conventional solar cell, and how this is improved by using hot-carrier, try the <a href="../freebies/quantumofsol/">Quantum of Sol Web App</a>. + </p> + </div> + <div class="span-6 last"> + <div> + <h3> + <span class="alt">Follow me here...</span> + </h3><a href="http://twitter.com/danieljfarrell"><img src="../img/twitter.jpg" width="35"></a> <a href="http://linkedin.com/in/danieljfarrell"><img src="../img/linkedin.jpg" width="33"></a> <a href="http://www.mendeley.com/profiles/daniel-farrell/"><img border="0" src="http://www.mendeley.com/embed/icon/1/blue/small" alt="Daniel Farrell's bibliography"></a> + </div> + <hr class="space"> + <hr class="space"> + <hr class="space"> + <hr class="space"> + <hr class="space"> + <hr class="space"> + <p> + <img src="../img/lsc.jpg" width="200" class="top push-0 shadow" alt="Luminescent solar concentrators."> + </p> + <div class="pcaption"> + <p> + Luminescent solar concentrators. + </p> + </div> <hr class="space"> <hr class="space"> <hr class="space"> <hr class="space"> <hr class="space"> <hr class="space"> <hr class="space"> <hr class="space"> <hr class="space"> - <p> - <img src="hccell.jpg" width=240 class="top push-0 shadow" alt="Hot-carrier solar cell."> - <div class="pcaption"> - <p>The hot-carrier solar cell.</p></div> + <img src="hccell.jpg" width="200" class="top push-0 shadow" alt="Hot-carrier solar cell."> </p> - + <div class="pcaption"> + <p> + The hot-carrier solar cell. + </p> + </div> </div> + </div> + <hr class="space"> + <hr class="space"> + <hr class="space"> + <hr class="space"> - </div> - -</body> + </body> </html>
danieljfarrell/website-2.0
734aeeb3f58c91caf855bfa1a9222041194b68d6
First additions to research page.
diff --git a/research/index.html b/research/index.html index c7709e3..93fe70e 100644 --- a/research/index.html +++ b/research/index.html @@ -1,86 +1,83 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London" /> <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated" /> <meta name="author" content="Daniel J Farrell" /> <title>Daniel J Farrell</title> <!-- Framework CSS --> <link rel="stylesheet" href="../blueprint/screen.css" type="text/css" media="screen, projection"> <link rel="stylesheet" href="../blueprint/print.css" type="text/css" media="print"> <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> <!-- Import fancy-type plugin --> <link rel="stylesheet" href="../blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> <link rel="stylesheet" href="../blueprint/plugins/navigation/sliding.css" type="text/css" media="screen, projection" /> </head> <body> <hr class="space"> <hr class="space"> <hr class="space"> <hr class="space"> <div class="container"> - - <div class="span-6"> - <h1 class="light">Daniel J Farrell</h1> - </div> + <div class="span-21 header"> + + <div class="span-6"> + <h1 class="light">Daniel J Farrell</h1> + </div> - <div class="push-1 span-13"> - <ul class="green"> - <li class="green"><a href="../index.html" title="home" ><span>home</span></a></li> - <li class="green"><a href="index.html" title="research" class="current"><span>research</span></a></li> - <li class="green"><a href="../freebies/index.html" title="freebies"><span>freebies</span></a></li> - <li class="green" ><a href="../contact/index.html" title="contact"><span>contact</span></a></li> - </ul> - </div> - - <hr class="space"> + <div class="push-1 span-13 last "> + + <ul class="green"> + <li class="green"><a href="../index.html" title="home" ><span>home</span></a></li> + <li class="green"><a href="index.html" title="research" class="current"><span>research</span></a></li> + <li class="green"><a href="../freebies/index.html" title="freebies"><span>freebies</span></a></li> + <li class="green" ><a href="../contact/index.html" title="contact"><span>contact</span></a></li> + </ul> + </div> - <div class="span-6"> - <img src="imdaniel_j_farrell.jpg" class="top push-0 shadow" alt="test" width="240px"> </div> - <div class="span-6 push-1 colborder"> - <h6>About</h6> - <p>Daniel is presently a post doctoral researcher in the Experimental Solid State Physics group at Imperial College London. His research activities revolve around approaches to increase the efficiency and reduce the cost of solar energy conversion and include: hot-carrier solar cells and spectral modification with luminescent materials.</p> - </div> - - <p> - <h3><span class="alt">Follow me here...</span></h3> - <a href="http://twitter.com/danieljfarrell"> <img src="../img/twitter.jpg" width="35"/></a> - <a href="http://linkedin.com/in/danieljfarrell"> <img src="../img/linkedin.jpg" width="33"/></a> - <a href="http://www.mendeley.com/profiles/daniel-farrell/"><img border="0" src="http://www.mendeley.com/embed/icon/1/blue/small" alt="Daniel Farrell's bibliography"/></a> - </p> - + <hr class="space"> - <div class="span-13 last"> - <hr> - <h3 class=""> Recent publications and talks</h3> - <ul class="publist"> - <li class="pub">D J Farrell and N J Ekins-Daukes, <em>"Photovoltaic technology: Relay dye boosts efficiency"</em>, <strong>Nature Photonics</strong>, 2009, 3: 373 - 374. <a href="http://doi:10.1038/nphoton.2009.108">doi:10.1038/nphoton.2009.108 -</a></li> - <li class="pub">D J Farrell, W G J H M van Sark, S T Velthuijsen and R E I Schropp, R, 2010, <em>"Using amorphous silicon solar cells to boost the viability of luminescent solar concentrators"</em>. <strong>Physica Status Solidi (c)</strong>, 7: 1045–1048. <a href="http://dx.doi.org/10.1002/pssc.200982866">doi:10.1002/pssc.200982866</a></li> + <div class="span-12 colborder"> + <h3>Research interests</h3> - <li class="publist"> - D J Farrell, <em>The next generation of Building Integrated Photovoltaics.</em>", presented to <a class="loud" href="http://www.arup.com">Arup Associates</a>, London 2009. - </li> - </ul> - </div> - + <h5>Hot-carrier solar cell</h5> + + <p>The hot-carrier solar cell is one of the most ambitious attempts at making the ultimate photovoltaic converter. It has the potential to eliminate both thermalisation and below bandgap losses. In this concept, thermalisation losses are eliminated using a mechanism prevents charge carriers from interacting with the lattice. Energy that would otherwise transfer to the lattice is stored in the carrier population as heat. In theory this enables very high conversion efficiencies because a low bandgap material can be chosen to maximise absorption across the spectrum, and still achieve high efficiency.</p> + + <h5>Luminescent solar concentrators</h5> + + <p>As well as being efficiency, the other factor driving photovoltaic research is the reduction of costs. High efficiency approaches are best suited to large power-plant installation. What is important for the average consumer or small business wishing to install solar panels is the <em>cost-per-Watt</em> of the technology: how much power power is generated for the amount of money spent.</p> + + + <p>The luminescent concentrator is a non-tracking approach to the concentration of solar energy. One very important feature of the luminescent concentrator is that it collects diffuse light as well as direct. This is significant, especially for high latitudes where the diffuse can account for 60% of the total insolation. The luminescent concentrator aims to reduced the cost-per-watt of generated power. This is achieved by the geometric and photon concentration factors between the top and edge surfaces.</p> + </div> + <div class="span-6 last"> + <hr class="space"> + <hr class="space"> + <hr class="space"> + <p> + <img src="../img/lsc.jpg" width=240 class="top push-0 shadow" alt="Luminescent solar concentrators"> + <div class="pcaption"> + <p>Luminescent solar concentrators.</p></div> + </p> + </div> </div> </body> </html>
danieljfarrell/website-2.0
679eecef4e471d87d168dd879c14eaaf100cbe56
Home and contact complete.
diff --git a/blueprint/.DS_Store b/blueprint/.DS_Store index dafd66d..9c953a1 100644 Binary files a/blueprint/.DS_Store and b/blueprint/.DS_Store differ diff --git a/blueprint/plugins/.DS_Store b/blueprint/plugins/.DS_Store index c4831de..32ccb90 100644 Binary files a/blueprint/plugins/.DS_Store and b/blueprint/plugins/.DS_Store differ diff --git a/blueprint/plugins/navigation/.DS_Store b/blueprint/plugins/navigation/.DS_Store new file mode 100644 index 0000000..f23cd23 Binary files /dev/null and b/blueprint/plugins/navigation/.DS_Store differ diff --git a/blueprint/plugins/navigation/css-sliding-door-blue.html b/blueprint/plugins/navigation/css-sliding-door-blue.html new file mode 100755 index 0000000..e9dd55a --- /dev/null +++ b/blueprint/plugins/navigation/css-sliding-door-blue.html @@ -0,0 +1,19 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> +<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> +<title>CSS Sliding Door with 1 image (Blue)</title> +<link rel="stylesheet" href="sliding.css" type="text/css" media="screen" /> +</head> + +<body> + +<ul class="blue"> + <li><a href="#" title="home" class="current"><span>home</span></a></li> + <li><a href="#" title="products"><span>products</span></a></li> + <li><a href="#" title="blog"><span>blog</span></a></li> + <li><a href="#" title="contact"><span>contact</span></a></li> +</ul> + +</body> +</html> diff --git a/blueprint/plugins/navigation/css-sliding-door.html b/blueprint/plugins/navigation/css-sliding-door.html new file mode 100755 index 0000000..09dec3a --- /dev/null +++ b/blueprint/plugins/navigation/css-sliding-door.html @@ -0,0 +1,40 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> +<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> +<title>CSS Sliding Door with 1 image (improved)</title> +<link rel="stylesheet" href="sliding.css" type="text/css" media="screen" /> +</head> + +<body> + +<ul class="green"> + <li><a href="#" title="home" class="current"><span>home</span></a></li> + <li><a href="#" title="products"><span>products</span></a></li> + <li><a href="#" title="blog"><span>blog</span></a></li> + <li><a href="#" title="contact"><span>contact</span></a></li> +</ul> + +<ul class="blue"> + <li><a href="#" title="home" class="current"><span>home</span></a></li> + <li><a href="#" title="products"><span>products</span></a></li> + <li><a href="#" title="blog"><span>blog</span></a></li> + <li><a href="#" title="contact"><span>contact</span></a></li> +</ul> + +<ul class="pink"> + <li><a href="#" title="home" class="current"><span>home</span></a></li> + <li><a href="#" title="products"><span>products</span></a></li> + <li><a href="#" title="blog"><span>blog</span></a></li> + <li><a href="#" title="contact"><span>contact</span></a></li> +</ul> + +<ul class="red"> + <li><a href="#" title="home" class="current"><span>home</span></a></li> + <li><a href="#" title="products"><span>products</span></a></li> + <li><a href="#" title="blog"><span>blog</span></a></li> + <li><a href="#" title="contact"><span>contact</span></a></li> +</ul> + +</body> +</html> diff --git a/blueprint/plugins/navigation/images/.DS_Store b/blueprint/plugins/navigation/images/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/blueprint/plugins/navigation/images/.DS_Store differ diff --git a/blueprint/plugins/navigation/images/blue.png b/blueprint/plugins/navigation/images/blue.png new file mode 100755 index 0000000..677356a Binary files /dev/null and b/blueprint/plugins/navigation/images/blue.png differ diff --git a/blueprint/plugins/navigation/images/green.png b/blueprint/plugins/navigation/images/green.png new file mode 100755 index 0000000..526a7c1 Binary files /dev/null and b/blueprint/plugins/navigation/images/green.png differ diff --git a/blueprint/plugins/navigation/images/pink.png b/blueprint/plugins/navigation/images/pink.png new file mode 100755 index 0000000..934515a Binary files /dev/null and b/blueprint/plugins/navigation/images/pink.png differ diff --git a/blueprint/plugins/navigation/images/red.png b/blueprint/plugins/navigation/images/red.png new file mode 100755 index 0000000..d2f2d1a Binary files /dev/null and b/blueprint/plugins/navigation/images/red.png differ diff --git a/blueprint/plugins/navigation/sliding-door.psd b/blueprint/plugins/navigation/sliding-door.psd new file mode 100755 index 0000000..2f28aac Binary files /dev/null and b/blueprint/plugins/navigation/sliding-door.psd differ diff --git a/blueprint/plugins/navigation/sliding.css b/blueprint/plugins/navigation/sliding.css new file mode 100755 index 0000000..6ed68d1 --- /dev/null +++ b/blueprint/plugins/navigation/sliding.css @@ -0,0 +1,91 @@ + + +ul.green { + padding: 5px; + margin: 10px 0; + list-style: none; + background-color: #fff; + border-bottom: 1px solid #e7e7e7; + float: left; + clear: left; +} + +ul.green li { + float: left; + display: inline; /*For ignore double margin in IE6*/ + margin: 0 22px; +} + +ul.green li a { + text-decoration: none; + float:left; + color: #999; + cursor: pointer; + font: 900 14px/22px "Arial", Helvetica, sans-serif; +} + +ul.green li a span { + margin: 0 10px 0 -10px; + padding: 1px 8px 5px 18px; + position: relative; /*To fix IE6 problem (not displaying)*/ + float:left; +} + +/*GREEN*/ + +ul.green li a.current, ul.green li a:hover { + color: #797979; + background: url(images/none.png) no-repeat top right; +} + +ul.green li a.current span, ul.green li a:hover span { + background: url(images/none.png) no-repeat top left; +} + +/*BLUE*/ +ul.blue li a.current, ul.blue li a:hover { + background: url(images/blue.png) no-repeat top right; + color: #0d5f83; +} + +ul.blue li a.current span, ul.blue li a:hover span { + background: url(images/blue.png) no-repeat top left; +} + +/*PINK*/ +ul.pink li a:hover { + color: #860737; + background: url(images/pink.png) no-repeat top right; +} + +ul.pink li a:hover span { + background: url(images/pink.png) no-repeat top left; +} + +ul.pink li a.current { + background: url(images/pink.png) no-repeat top right; + color: #860737; +} + +ul.pink li a.current span { + background: url(images/pink.png) no-repeat top left; +} + +/*RED*/ +ul.red li a:hover { + color: #fff; + background: url(images/red.png) no-repeat top right; +} + +ul.red li a:hover span { + background: url(images/red.png) no-repeat top left; +} + +ul.red li a.current { + background: url(images/red.png) no-repeat top right; + color: #fff; +} + +ul.red li a.current span { + background: url(images/red.png) no-repeat top left; +} \ No newline at end of file diff --git a/contact/.DS_Store b/contact/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/contact/.DS_Store differ diff --git a/contact/ic.jpg b/contact/ic.jpg new file mode 100644 index 0000000..8893ed1 Binary files /dev/null and b/contact/ic.jpg differ diff --git a/contact/ic_location.jpg b/contact/ic_location.jpg new file mode 100644 index 0000000..250545b Binary files /dev/null and b/contact/ic_location.jpg differ diff --git a/contact/index.html b/contact/index.html new file mode 100644 index 0000000..419a99b --- /dev/null +++ b/contact/index.html @@ -0,0 +1,103 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> + +<html lang="en"> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London" /> + <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated" /> + <meta name="author" content="Daniel J Farrell" /> + <meta name="microid" content="mailto+http:sha1:ab095e627455a292fb5fd60550b0fa4a2105ae79" /> + <link rel="openid.server" href="http://openid.claimid.com/server" /> + <link rel="openid.delegate" href="http://daniel.farrell.name" /> + <title>Daniel J Farrell</title> + + <!-- Framework CSS --> + <link rel="stylesheet" href="../blueprint/screen.css" type="text/css" media="screen, projection"> + <link rel="stylesheet" href="../blueprint/print.css" type="text/css" media="print"> + <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> + + <!-- Import fancy-type plugin --> + <link rel="stylesheet" href="../blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> + + <link rel="stylesheet" href="../blueprint/plugins/navigation/sliding.css" type="text/css" media="screen, projection" /> + +</head> + +<body> + + <hr class="space"> + <hr class="space"> + <hr class="space"> + <hr class="space"> + + + <div class="container"> + + + <div class="span-6"> + <h1 class="light">Daniel J Farrell</h1> + </div> + + <div class="push-1 span-13"> + + <ul class="green"> + <li class="green"><a href="../index.html" title="home" ><span>home</span></a></li> + <li class="green"><a href="../research/index.html" title="research" ><span>research</span></a></li> + <li class="green"><a href="../freebies/index.html" title="freebies"><span>freebies</span></a></li> + <li class="green" ><a href="index.html" title="contact" class="current"><span>contact</span></a></li> + </ul> + </div> + + <hr class="space"> + + <div class="span-6"> + <h6>At Imperial College London</h6> + <hr class="space"> + <a href="http://maps.google.co.uk/maps/place?cid=17449252295702573143&q=imperial+college+london+physics+department&hl=en&gl=uk"><img src="ic.jpg" alt="Location of Imperial College Department of Physics" width="260"></a> + </div> + <div class="span-6 push-2"> + + <h6>On the web</h6> + <hr class="space"> + <a href="http://twitter.com/danieljfarrell"> <img src="../img/twitter.jpg" width="35"/></a> + <a href="http://linkedin.com/in/danieljfarrell"> <img src="../img/linkedin.jpg" width="33"/></a> + <a href="http://www.mendeley.com/profiles/daniel-farrell/"><img border="0" src="http://www.mendeley.com/embed/icon/1/blue/small" + </div> + + + <div class="span-3 push-1"> + + <h6>On Skype</h6> + <hr class="space"> + <!-- +Skype 'My status' button +http://www.skype.com/go/skypebuttons +--> +<script type="text/javascript" src="http://download.skype.com/share/skypebuttons/js/skypeCheck.js"></script> +<a href="skype:daniel.james.farrell?call"><img src="http://mystatus.skype.com/balloon/daniel%2Ejames.farrell" style="border: none;" width="150" height="60" alt="My status" /></a> + </div> + + <hr class="space"> + <hr class="space"> + + <div class=" span-5"> + + <p>Dr. Daniel J Farrell<br> + Experimental Solid State Physics<br> + Blackett Laboratory,<br> + Imperial College London,<br> + Prince Consort Road,<br> + London SW7 2AZ.<br> + U.K. <br> + e-mail: <a href="mailto:[email protected]">[email protected]</a><br> + tel: (+44) - (0)20 7594 7305 + </p> + </div> + + + </div> + </div> + +</body> +</html> diff --git a/freebies/index.html b/freebies/index.html new file mode 100644 index 0000000..9e4a60e --- /dev/null +++ b/freebies/index.html @@ -0,0 +1,86 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> + +<html lang="en"> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London" /> + <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated" /> + <meta name="author" content="Daniel J Farrell" /> + <title>Daniel J Farrell</title> + + <!-- Framework CSS --> + <link rel="stylesheet" href="../blueprint/screen.css" type="text/css" media="screen, projection"> + <link rel="stylesheet" href="../blueprint/print.css" type="text/css" media="print"> + <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> + + <!-- Import fancy-type plugin --> + <link rel="stylesheet" href="../blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> + + <link rel="stylesheet" href="../blueprint/plugins/navigation/sliding.css" type="text/css" media="screen, projection" /> + +</head> + +<body> + + <hr class="space"> + <hr class="space"> + <hr class="space"> + <hr class="space"> + + + <div class="container"> + + + <div class="span-6"> + <h1 class="light">Daniel J Farrell</h1> + </div> + + <div class="push-1 span-13"> + <ul class="green"> + <li class="green"><a href="../index.html" title="home" ><span>home</span></a></li> + <li class="green"><a href="../research/index.html" title="research"><span>research</span></a></li> + <li class="green"><a href="index.html" title="freebies" class="current"><span>freebies</span></a></li> + <li class="green" ><a href="../contact/index.html" title="contact"><span>contact</span></a></li> + </ul> + </div> + + <hr class="space"> + + <div class="span-6"> + <img src="imdaniel_j_farrell.jpg" class="top push-0 shadow" alt="test" width="240px"> + </div> + + <div class="span-6 push-1 colborder"> + <h6>About</h6> + <p>Daniel is presently a post doctoral researcher in the Experimental Solid State Physics group at Imperial College London. His research activities revolve around approaches to increase the efficiency and reduce the cost of solar energy conversion and include: hot-carrier solar cells and spectral modification with luminescent materials.</p> + </div> + + <p> + <h3><span class="alt">Follow me here...</span></h3> + <a href="http://twitter.com/danieljfarrell"> <img src="../img/twitter.jpg" width="35"/></a> + <a href="http://linkedin.com/in/danieljfarrell"> <img src="../img/linkedin.jpg" width="33"/></a> + <a href="http://www.mendeley.com/profiles/daniel-farrell/"><img border="0" src="http://www.mendeley.com/embed/icon/1/blue/small" alt="Daniel Farrell's bibliography"/></a> + </p> + + + <div class="span-13 last"> + <hr> + <h3 class=""> Recent publications and talks</h3> + <ul class="publist"> + <li class="pub">D J Farrell and N J Ekins-Daukes, <em>"Photovoltaic technology: Relay dye boosts efficiency"</em>, <strong>Nature Photonics</strong>, 2009, 3: 373 - 374. <a href="http://doi:10.1038/nphoton.2009.108">doi:10.1038/nphoton.2009.108 +</a></li> + <li class="pub">D J Farrell, W G J H M van Sark, S T Velthuijsen and R E I Schropp, R, 2010, <em>"Using amorphous silicon solar cells to boost the viability of luminescent solar concentrators"</em>. <strong>Physica Status Solidi (c)</strong>, 7: 1045–1048. <a href="http://dx.doi.org/10.1002/pssc.200982866">doi:10.1002/pssc.200982866</a></li> + + <li class="publist"> + D J Farrell, <em>The next generation of Building Integrated Photovoltaics.</em>", presented to <a class="loud" href="http://www.arup.com">Arup Associates</a>, London 2009. + </li> + </ul> + </div> + + + + </div> + +</body> +</html> diff --git a/index.html b/index.html index 7dfc55e..4d9ea01 100644 --- a/index.html +++ b/index.html @@ -1,168 +1,89 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London" /> <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated" /> <meta name="author" content="Daniel J Farrell" /> <meta name="microid" content="mailto+http:sha1:ab095e627455a292fb5fd60550b0fa4a2105ae79" /> <link rel="openid.server" href="http://openid.claimid.com/server" /> <link rel="openid.delegate" href="http://daniel.farrell.name" /> <title>Daniel J Farrell</title> <!-- Framework CSS --> - <link rel="stylesheet" href="blueprint/screen.css" type="text/css" media="screen, projection"> - <link rel="stylesheet" href="blueprint/print.css" type="text/css" media="print"> + <link rel="stylesheet" href="blueprint/screen.css" type="text/css" media="screen, projection"> + <link rel="stylesheet" href="blueprint/print.css" type="text/css" media="print"> <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> + + <!-- Import fancy-type plugin --> + <link rel="stylesheet" href="blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> + + <link rel="stylesheet" href="blueprint/plugins/navigation/sliding.css" type="text/css" media="screen, projection" /> - <!-- Import fancy-type plugin for the sample page. --> - <link rel="stylesheet" href="blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> </head> <body> + <hr class="space"> + <hr class="space"> + <hr class="space"> + <hr class="space"> + + <div class="container"> + + <div class="span-6"> - <h1 class="light">Daniel J Farrell</h1> + <h1 class="light">Daniel J Farrell</h1> </div> - - - <!-- <h2 class="alt">Research Associate in quantum photovoltaics at Imperial College London</h2> --> + <div class="push-1 span-13"> + <ul class="green"> + <li class="green"><a href="index.html" title="home" class="current"><span>home</span></a></li> + <li class="green"><a href="research/index.html" title="research"><span>research</span></a></li> + <li class="green"><a href="freebies/index.html" title="freebies"><span>freebies</span></a></li> + <li class="green" ><a href="contact/index.html" title="contact"><span>contact</span></a></li> + </ul> + </div> <hr class="space"> - <div class="span-6"> - <img src="daniel_j_farrell.jpg" class="top push-0 shadow" alt="test" width="240px"> + <img src="img/daniel_j_farrell.jpg" class="top push-0 shadow" alt="test" width="240px"> </div> <div class="span-6 push-1 colborder"> - <h6>About</h6> - <p>Daniel is presently a post doctoral researcher in the Experimental Solid State Physics group at Imperial College London. His research activities revolve around approaches to increase the efficiency and reduce the cost of solar energy conversion and include: hot-carrier solar cells and spectral modification with luminescent materials.</p> - + <h6>About</h6> + <p>Daniel is presently a post doctoral researcher in the Experimental Solid State Physics group at Imperial College London. His research activities revolve around approaches to increase the efficiency and reduce the cost of solar energy conversion and include: hot-carrier solar cells and spectral modification with luminescent materials.</p> </div> - <!-- - <div class="span-6 colborder"> - <h6>Research Interests</h6> - <ul> - <li>Hot-carrier solar cells</li> - <li>Thermodynamic modelling of solar energy convertors</li> - <li>Luminescent solar concentrators</li> - <li>Nano-materials: - <ul class="nest-2"><li>Quantum dots and rods</li> - <li>Organic dyes</li> - </ul> - <li>Building integrated photovoltaics</li> - <li>Thin-film optical coatings</li> - <li>Monte-Carlo optical modelling</li> - </ul> - </div> - --> + <p> + <h3><span class="alt">Follow me here...</span></h3> + <a href="http://twitter.com/danieljfarrell"> <img src="img/twitter.jpg" width="35"/></a> + <a href="http://linkedin.com/in/danieljfarrell"> <img src="img/linkedin.jpg" width="33"/></a> + <a href="http://www.mendeley.com/profiles/daniel-farrell/"><img border="0" src="http://www.mendeley.com/embed/icon/1/blue/small" alt="Daniel Farrell's bibliography"/></a> + </p> - <div class="span-5 last"> - <h6>Contact</h6> - <p>Dr. Daniel J Farrell<br> - Experimental Solid State Physics<br> - Blackett Laboratory,<br> - Imperial College London,<br> - Prince Consort Road,<br> - London SW7 2AZ.<br> - U.K. <br> - e-mail: <a href="mailto:[email protected]">[email protected]</a><br> - tel: (+44) - (0)20 7594 7305 - </p> - </div> - <hr> - <div class="span-13 append-5 colborder"> - - <h1 class="alt"> Research</h1> - - <h3>The efficiency challenge</h3> - - <div style="float: right;" class="push-1 span-5"> - <h3 class="alt"><span class="dquo">&#8220;</span>The challenge for future research is to better harness the energy content of each photon.&#8221;</h3> - </div> - - <p> - Conventional solar cell are now, after many decades of research and development, beginning to approach their fundamental limits. These devices harvest <em>solar photons</em> and directly convert them to electrical current.</p> - - <div class"align-right"> - <img src="img/losses.jpg" width="410" alt="Fundamental losses in solar cells: thermalisation loss and below bandgap loss."/> - <p class="pcaption">Fundamental losses in solar cells: thermalisation loss and below bandgap loss.</p> - </div> - - <p>A spectrum of photons enter conventional solar cells: blue and UV photons possess high energy and red and infrared photons possess less energy. A semiconductor has an energy threshold that called the <em>bandgap</em> that is the minimum energy a photon needs to be absorbed. If a photon has less energy it will remain unabsorbed; from the perspective of the photon the material looks transparent. This is called <em>below bandgap loss</em>.</p> - - <p> - When electrons exit a solar cell they all eave with the same amount of energy (set by the voltage of device). However, light that generated these electrons has a large range of energies, thus during the conversion process energy has been lost. This is known as <em>thermalisation loss</em>. In conventional solar cells the energy of above bandgap photons is not utilised, it simply wasted as lattice vibrations (heat).</p> - - <div> - <img src="http://chart.apis.google.com/chart?chxs=0,676767,16&chxt=x&chs=410x150&cht=p3&chco=B4C7AB|C2CEE4|9B8A9D|3366CC&chd=s:TVV&chdl=Power|Thermalisation|Unabsorbed&chl=31%25|34%25|35%25" width="410" height="150" alt="" /> - <p class="pcaption">Where does the energy go?</p> - </div> - - <p>In today's best solar cells the power extracted is less than 1/3 of the solar power that was incident. The pie chart show how the absorbed energy divides up into useful power generation, and the losses processes.</p> - <p> - The challenge for future research is to better harness the energy content of each photon. Moreover, rather than just capturing solar photons in a one-to-one conversion process we must address how the <em>solar energy</em> carried by each photon can be utilised to the fullest potential.</p> - - <h3>Hot-carrier solar cells</h3> - - <p>The hot-carrier solar cell is one of the most ambitious attempts at making the ultimate photovoltaic converter. It has the potential to eliminate both thermalisation and below bandgap losses. In this concept, thermalisation losses are eliminated using a mechanism prevents charge carriers from interacting with the lattice. Energy that would otherwise transfer to the lattice is stored in the carrier population as heat. In theory this enables very high conversion efficiencies because a low bandgap material can be chosen to maximise absorption across the spectrum, and still achieve high efficiency.</p> - - <h5>Luminescent solar concentrators</h5> - - <p>As well as being efficiency, the other factor driving photovoltaic research is the reduction of costs. High efficiency approaches are best suited to large power-plant installation. What is important for the average consumer or small business wishing to install solar panels is the <em>cost-per-Watt</em> of the technology: how much power power is generated for the amount of money spent.</p> - - <img src="img/lsc.jpg" class="top push-0 shadow" alt="Luminescent solar concentrators"> - <div class="pcaption"> - <p>Luminescent solar concentrators.</p></div> - - <p>The luminescent concentrator is a non-tracking approach to the concentration of solar energy. One very important feature of the luminescent concentrator is that it collects diffuse light as well as direct. This is significant, especially for high latitudes where the diffuse can account for 60% of the total insolation. The luminescent concentrator aims to reduced the cost-per-watt of generated power. This is achieved by the geometric and photon concentration factors between the top and edge surfaces.</p> - - <h5>Quantum Dots</h5> - <p>Quantum dots are nanoscale crystals of semiconductor materials. One interesting feature of quantum dots is that their optical properties are size dependent. This is because of <em>quantum confinement</em> of the electron and hole wavefunctions. Our group has proposed replacing organic dyes with quantum dots in luminescent concentrators. This has several advantages; emission colour can be changed by changing the particle size, large red-shifts can be produced by controlling the spread in dot sizes and quantum dots should be inherently more stable than organic materials.</p> + <div class="span-13 last"> <hr> - <div class="span-13 last"> - <h5> Recent publications and talks</h5> + <h3 class=""> Recent publications and talks</h3> <ul class="publist"> - <li class="pub">D J Farrell and N J Ekins-Daukes, <strong>"Photovoltaic technology: Relay dye boosts efficiency"</strong>, <a href="http://dx.doi.org/10.1038/nphoton.2009.108">Nature Photonics 3, 373 - 374 (2009) </a></li> - <li class="pub">D J Farrell, Wilfried G J H M van Sark, S T Velthuijsen, R E I Schropp, <strong>Using amorphous silicon solar cells to boost the viability of Luminescent Solar Concentrators</strong>, <a href="http://www.icans23.org">23rd International Conference on Amorphous and Nanocrystalline Semiconductors</a>, August 2009 (<a href="publications/farrell-icans23.pdf">Download Pre-print</a>).</li> + <li class="pub">D J Farrell and N J Ekins-Daukes, <em>"Photovoltaic technology: Relay dye boosts efficiency"</em>, <strong>Nature Photonics</strong>, 2009, 3: 373 - 374. <a href="http://doi:10.1038/nphoton.2009.108">doi:10.1038/nphoton.2009.108 +</a></li> + <li class="pub">D J Farrell, W G J H M van Sark, S T Velthuijsen and R E I Schropp, R, 2010, <em>"Using amorphous silicon solar cells to boost the viability of luminescent solar concentrators"</em>. <strong>Physica Status Solidi (c)</strong>, 7: 1045–1048. <a href="http://dx.doi.org/10.1002/pssc.200982866">doi:10.1002/pssc.200982866</a></li> <li class="publist"> - D J Farrell, <strong>"<a href="publications/arup.html">The next generation of Building Integrated Photovoltaics</a>"</strong>, <a href="http://www.arup.com">Arup Associates</a>, London, (2009). + D J Farrell, <em>The next generation of Building Integrated Photovoltaics.</em>", presented to <a class="loud" href="http://www.arup.com">Arup Associates</a>, London 2009. </li> - <li> - <a href="publications/index.html">Full publication list.</a> - </li> </ul> </div> - </div> - <div class="span-6 last"> - <p> - <h3><span class="alt">Follow me here...</span></h3> - <a href="http://twitter.com/danieljfarrell"> <img src="img/twitter.jpg" width="35"/></a> - <a href="http://linkedin.com/in/danieljfarrell"> <img src="img/linkedin.jpg" width="33"/></a> - <a href="http://www.mendeley.com/profiles/daniel-farrell/"><img border="0" src="http://www.mendeley.com/embed/icon/1/blue/small" alt="Daniel Farrell's bibliography"/></a> - </p> - <hr class="space"> - <p> - <h3><span class="alt">Imperial College London</span></h3> - <a href="http://www.imperial.ac.uk/qpv">Quantum Photovoltaics Group</a> - </p> - <hr class="space"> - <p> - <h3><span class="alt">My bookmarks</span></h3> - <script type="text/javascript" src="http://feeds.delicious.com/v2/js/boyfarrell?title=&icon=m&count=15&sort=date&extended"></script></p> + + - </div> - <hr> - <p class="light">Updated: 5th July 2009</p> </div> </body> </html> diff --git a/publications/arup.html b/publications/arup.html deleted file mode 100644 index 4f62016..0000000 --- a/publications/arup.html +++ /dev/null @@ -1,115 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html> -<head> - <meta name="description" content="Dr. Daniel J Farrell Quantum Photovoltaics Group Imperial College London http://sc.ic.ac.uk/~q_pv http://www.imperial.ac.uk/qpv The next generation of building integrated photovoltaics Acknowledgements The rest of the Quantum Photovoltaics Group: Ben Browne, Louise Hirst, Rahul Bose, Jessica Adams, Markus Fuhrer, 
Ravin Ginige, Mauro Pravettoni Ned
Ekins-Daukes Keith Barnham Amanda Chatten Outline What is Photovoltaics? Present building integrated photovoltaics: Silicon modules Thin-film facades The next generation... “Smart windows” Direct system Direct + Diffuse system Light-bars Acronyms: Photovoltaics = PV Building Integrated PV = BIPV A photovoltaic cell (a.k.a solar cell) behaves like a battery But only gives out power when light hits it Particles of light are called photons What is photovoltaics? Why Building Integrated Photovoltaics (BIPV)? Motivation: Local generation of power when demand is high In the UK 7x the solar energy falls on commercial building than is used inside K.Barnham et al. Nature Materials 5, 161 - 164 (2006)
doi:10.1038/nmat1604 We are treating the solar energy as a problem, but it’s a solution! Blinds to blocklight still require air-con. and lighting. What is photovoltaics?- Efficiency The performance of solar cell is its efficiency efficiency = power out / power in For example: A 1m2 solar cell has... 1000 Watts of solar power incident Produces 200 Watts of electrical power Efficiency = 20% Solar power in Electrical power out What is photovoltaics?- Cost High efficiency must be affordable! Another way of saying this is: What is the cost per Watt of the generated electricity? The cost per Watt should be minimised Current fossil fuel technology can generated electrical power at $1/W Where is photovoltaics in this respect? “This is the world's lowest-cost solar panel, which we believe will make us the first solar manufacturer capable of profitably selling solar panels at as little as 99 cents a watt.” -- Nanosolar, 2008 3 generations of photovoltaics 0 100 200 300 400 500 20 40 60 80 100 Efficiency (%) Cost in US$ for a 1m2 solar module US$0.10/W US$0.20/W US$0.50/W US$1.00/W US$3.50/W Adapted from original by M.Green, UNSW. Examples of 1st and 2nd generation BIPV 1st generation BIPV CIS building Manchester Solar installation by Solar Century 391 kWatts capacity 3200 square meter coverage (122 Wm-2) Can this provide all the power needs? 1st generation BIPV Design options: Utilitarian It gets the job done Bolt on design Truly integrate PV? http://www.solarcentury.co.uk 1st generation BIPV http://www.solarcentury.co.uk Vauxhall Cross, London Designed to incorporate the panels Advances in shape and colour PV Crystalox and NaREC Development of coloured anti-reflection Advances is laser cutting 2nd generation BIPV Can be made semi-transparent Beginning to be truly building integrated. 5%-12% efficiency Arnold Glas, Voltarlux Windows 1st and 2nd generation re-cap Photovoltaic material is made into panels 1st generation silicon wafers 2nd thin-film silicon, CdTe, CIGS, dye-sensitised solar cells 0 100 200 300 400 500 20 40 60 80 100 Efficiency (%) Cost in US$ for a 1m2 solar module US$0.10/W US$0.20/W US$0.50/W US$1.00/W US$3.50/W 1st 1. Conventional silicon PV (Wafer based c-Si) 2. Conventional thin-film PV (a-Si, CdTe) 2nd 3rd generation PV is a ‘concentrator technology’ 3rd generation PV uses: high efficiency materials (e.g. GaAs). very small areas of cell, ~1mm2 very large area of lens and mirror. The lens and mirror used concentrate the sun between 100--1000 times. Concentrator PV farm - SolFocus How can we use 3rd generation PV in buildings? Roof installations: Provide electricity and hot water to the building. 15% efficient PV conversion 45% efficient hot water generation John F.H. Smeltink and Andrew W. Blakers The next generation of BIPV Smart Windows - “Solar Skin from Solar Structure” Smart Windows: Keith Barnham, 2006. Smart Windows Smart Windows: Direct light absorbed Diffuse enters room Lower demand on 
air-conditioning Provides heat and electricity Advantages of the Smart Window concept The direct light is total absorbed in the solar cells: Does not cause interior heating Reduces air-conditioning loads AND produces electricity AND produces hot-water Diffuse light illuminates the room No glare Just diffuse blue sky and white light How does the smart window compare to 2nd generation building integrated PV? Diffuse 2nd Generation
 thin-silicon windows 3rd Generation 
smart windows Direct 21% Electricity Interior illumination 35% 5% 5% 12% Electricity 65% Heat dispersion 22% Heating 78% 65% 22% It’s not sunny all the time... In the UK approx. 50% of the yearly solar energy arrives as diffuse light. Smart Window can still generate significant amount of power Can we design and building integrated system to harvest the diffuse component...? Blue sky and clouds. Luminescent solar concentrators Diffuse Direct Solar cells placed on edges Advantages for BIPV: Concentrates direct and diffuse illumination Interesting colours Interesting shapes Depending on colour and size, 5% efficiency. Non-tracking Freedom to design Luminescent materials in BIPV Luminescent materials in BIPV Mauro Pravettoni Can select shape and colour 5% efficiency Useful for decoration Facades Windows.....? Luminescent materials in BIPV Transparent luminescent materials Tinted windows work well for facades and decoration Windows should remain transparent Absorb invisible wavelengths of light: Ultra-violet (UV) and Infrared (IR). Currently only UV absorbing luminescent materials exist. Smart windows with UV booster Diffuse 3rd Generation 
smart windows Direct 21% Electricity Interior illumination 35% Heat dispersion 22% Heating 65% 22% 33% 23% Electricity 2% absolute gain by using the UV with a luminescent solar concentrator Light-bar smart window Alternative smart window design: Light-bar Remove non-transparent components from the window Dramatically reduces cost Price per watt reduces too. Sunlight focused on to bars that pipe the light to edges. 5%-10% efficiency Conclusion: the next generation of BIPV High efficiency 3rd Generation photovoltaics Integrated into Smart Windows Provide power and heat Reduce air-condition and provide illumination Truly building integrated Coloured luminescent materials as facades and decoration Design freedom UV + IR transparent luminescent materials for windows Boost Smart Window power output all year round Light-bar allow totally transparent Smart Window"/> - <title></title> - <script type="text/javascript" language="javascript"> -// <![CDATA[ - var images = new Array (72); - images[0] = "arup.html_files/arup.001-001.png"; - images[1] = "arup.html_files/arup.002-001.png"; - images[2] = "arup.html_files/arup.003-001.png"; - images[3] = "arup.html_files/arup.003-002.png"; - images[4] = "arup.html_files/arup.004-001.png"; - images[5] = "arup.html_files/arup.004-002.png"; - images[6] = "arup.html_files/arup.004-003.png"; - images[7] = "arup.html_files/arup.004-004.png"; - images[8] = "arup.html_files/arup.005-001.png"; - images[9] = "arup.html_files/arup.006-001.png"; - images[10] = "arup.html_files/arup.006-002.png"; - images[11] = "arup.html_files/arup.006-003.png"; - images[12] = "arup.html_files/arup.006-004.png"; - images[13] = "arup.html_files/arup.007-001.png"; - images[14] = "arup.html_files/arup.007-002.png"; - images[15] = "arup.html_files/arup.008-001.png"; - images[16] = "arup.html_files/arup.008-002.png"; - images[17] = "arup.html_files/arup.008-003.png"; - images[18] = "arup.html_files/arup.008-004.png"; - images[19] = "arup.html_files/arup.009-001.png"; - images[20] = "arup.html_files/arup.010-001.png"; - images[21] = "arup.html_files/arup.011-001.png"; - images[22] = "arup.html_files/arup.012-001.png"; - images[23] = "arup.html_files/arup.013-001.png"; - images[24] = "arup.html_files/arup.014-001.png"; - images[25] = "arup.html_files/arup.015-001.png"; - images[26] = "arup.html_files/arup.016-001.png"; - images[27] = "arup.html_files/arup.017-001.png"; - images[28] = "arup.html_files/arup.017-002.png"; - images[29] = "arup.html_files/arup.018-001.png"; - images[30] = "arup.html_files/arup.019-001.png"; - images[31] = "arup.html_files/arup.020-001.png"; - images[32] = "arup.html_files/arup.021-001.png"; - images[33] = "arup.html_files/arup.022-001.png"; - images[34] = "arup.html_files/arup.022-002.png"; - images[35] = "arup.html_files/arup.022-003.png"; - images[36] = "arup.html_files/arup.023-001.png"; - images[37] = "arup.html_files/arup.023-002.png"; - images[38] = "arup.html_files/arup.023-003.png"; - images[39] = "arup.html_files/arup.023-004.png"; - images[40] = "arup.html_files/arup.023-005.png"; - images[41] = "arup.html_files/arup.023-006.png"; - images[42] = "arup.html_files/arup.024-001.png"; - images[43] = "arup.html_files/arup.025-001.png"; - images[44] = "arup.html_files/arup.026-001.png"; - images[45] = "arup.html_files/arup.027-001.png"; - images[46] = "arup.html_files/arup.028-001.png"; - images[47] = "arup.html_files/arup.029-001.png"; - images[48] = "arup.html_files/arup.029-002.png"; - images[49] = "arup.html_files/arup.029-003.png"; - images[50] = "arup.html_files/arup.029-004.png"; - images[51] = "arup.html_files/arup.029-005.png"; - images[52] = "arup.html_files/arup.029-006.png"; - images[53] = "arup.html_files/arup.030-001.png"; - images[54] = "arup.html_files/arup.030-002.png"; - images[55] = "arup.html_files/arup.030-003.png"; - images[56] = "arup.html_files/arup.031-001.png"; - images[57] = "arup.html_files/arup.031-002.png"; - images[58] = "arup.html_files/arup.031-003.png"; - images[59] = "arup.html_files/arup.031-004.png"; - images[60] = "arup.html_files/arup.031-005.png"; - images[61] = "arup.html_files/arup.031-006.png"; - images[62] = "arup.html_files/arup.031-007.png"; - images[63] = "arup.html_files/arup.031-008.png"; - images[64] = "arup.html_files/arup.032-001.png"; - images[65] = "arup.html_files/arup.032-002.png"; - images[66] = "arup.html_files/arup.032-003.png"; - images[67] = "arup.html_files/arup.032-004.png"; - images[68] = "arup.html_files/arup.032-005.png"; - images[69] = "arup.html_files/arup.032-006.png"; - images[70] = "arup.html_files/arup.032-007.png"; - images[71] = "arup.html_files/arup.032-008.png"; - var index = 0; - function WindowLoaded(evt) - { - document.body.onselectstart = function () { return false; }; - } - function Step(i) - { - GoTo(index + i) - } - function GoTo(newIndex) - { - if(newIndex >= 0 && newIndex < images.length) - { - index = newIndex; - document.Slideshow.src = images[index]; - } - } -// ]]> - </script> -</head> -<body bgcolor="black" onload='WindowLoaded(event);'> - <p align="center"> - <br/> - <br/> - <img name="Slideshow" alt="" src="arup.html_files/arup.001-001.png" onclick="Step(1)"/> - <br/> - <br/> - <input type="image" src="arup.html_files/home.png" onclick="GoTo(0)"/> - &nbsp;&nbsp;&nbsp; - <input type="image" src="arup.html_files/prev.png" onclick="Step(-1)"/> - <input type="image" src="arup.html_files/next.png" onclick="Step(1)"/> - </p> -</body> -</html> \ No newline at end of file diff --git a/publications/arup.html_files/arup.001-001.png b/publications/arup.html_files/arup.001-001.png deleted file mode 100644 index 6d6e92d..0000000 Binary files a/publications/arup.html_files/arup.001-001.png and /dev/null differ diff --git a/publications/arup.html_files/home.png b/publications/arup.html_files/home.png deleted file mode 100644 index 8914de3..0000000 Binary files a/publications/arup.html_files/home.png and /dev/null differ diff --git a/publications/arup.html_files/next.png b/publications/arup.html_files/next.png deleted file mode 100644 index ae8d51a..0000000 Binary files a/publications/arup.html_files/next.png and /dev/null differ diff --git a/publications/arup.html_files/prev.png b/publications/arup.html_files/prev.png deleted file mode 100644 index 0de9aa0..0000000 Binary files a/publications/arup.html_files/prev.png and /dev/null differ diff --git a/publications/farrell-icans23.pdf b/publications/farrell-icans23.pdf deleted file mode 100644 index 4590c5f..0000000 Binary files a/publications/farrell-icans23.pdf and /dev/null differ diff --git a/publications/index.html b/publications/index.html deleted file mode 100644 index 89ed94c..0000000 --- a/publications/index.html +++ /dev/null @@ -1,92 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" - "http://www.w3.org/TR/html4/strict.dtd"> - -<html lang="en"> -<head> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> - <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London" /> - <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated" /> - <meta name="author" content="Daniel J Farrell" /> - <meta name="microid" content="mailto+http:sha1:d88ae819ad27750216a14d0338bdd81fb38d2a9a" /> - <link rel="openid.server" href="http://openid.claimid.com/server" /> - <link rel="openid.delegate" href="http://openid.claimid.com/boyfarrell" /> - <title>Daniel J Farrell</title> - - <!-- Framework CSS --> - <link rel="stylesheet" href="../blueprint/screen.css" type="text/css" media="screen, projection"> - <link rel="stylesheet" href="../blueprint/print.css" type="text/css" media="print"> - <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> - - <!-- Import fancy-type plugin for the sample page. --> - <link rel="stylesheet" href="../blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> -</head> - -<body> - - <div class="container"> - - <!-- <h2 class="alt">Research Associate in quantum photovoltaics at Imperial College London</h2> --> - <hr> - <hr class="space"> - <a href="../index.html">Home</a> - <hr> - - - - <div class="span-13"> - <h5>Selected publications</h5> - <ul class="publist"> - <li class="pub">D J Farrell, W G J H M van Sark, S T Velthuijsen, R E I Schropp, <strong>Using amorphous silicon solar cells to boost the viability of Luminescent Solar Concentrators</strong>, <a href="http://www.icans23.org">23rd International Conference on Amorphous and Nanocrystalline Semiconductors</a>, August 2009 (<a href="farrell-icans23.pdf">Download Pre-print</a>).</li> - - <li class="pub">D J Farrell and N J Ekins-Daukes, <strong>Photovoltaic technology: Relay dye boosts efficiency</strong>, <a href="http://dx.doi.org/10.1038/nphoton.2009.108">Nature Photonics 3, 373 - 374 (2009) </a></li> - <li class="pub">D J Farrell, A J Chatten, A Büchtemann and K W J Barnham, <strong>“Fabrication, Characterisation and Modelling of Quantum Dot Solar Concentrator Stacks”</strong>, Proc. IEEE 4th World Conference on Photovoltaic Energy Conversion, (Waikoloa, Hawaii, 2006), p217.</li> - - <li class="pub">D J Farrell, A J Chatten, B F Buxton, A Büchtemann, R Danz, M Schleusener, L H Slooff, R Kinderman, A R Burgers, J A M van Roosmalen and K W J Barnham, <strong>“The Luminescent Concentrator: Large Area Modelling And Results With Dye Based Stack Concentrators And Thin-Film Composite Plates”</strong>, Proc. of the 20th European Photovoltaic Solar Energy Conference, (Barcelona, Spain, 2005), p386.</li> - - <li class="pub">D J Farrell, A J Chatten, B F Buxton and K W J Barnham, <strong>"Thermodynamic modelling of the Luminescent Solar Concentrator"</strong>, PVNet-3 UK Conference (Loughborough, UK, 2005).</li> - - </ul> - - <h5>Collaborations</h5> - <ul class="publist"> - <li class="pub">R Bose, D J Farrell, A J Chatten, A Büchtemann and K W J Barnham, <strong>“Luminescent Solar Concentrators”</strong>, Proc. Photovoltaic Science Applications and Technology (PVSAT-3), (Durham, UK, 2007), p63.</li> - - <li class="pub">A J Chatten D J Farrell, R Bose, M G Debije, A Büchtemann and K W J Barnham, <strong>“Thermodynamic Modelling of Luminescent Solar Concentrators with Reduced Top Surface Losses”</strong>, abstract accepted: 22nd European Photovoltaic Solar Energy Conference, (Milan, Italy, 2007).</li> - - <li class="pub">A J Chatten, D J Farrell, B F Buxton, A Büchtemann and K W J Barnham, <strong>“Thermodynamic Modelling of Luminescent Solar Concentrators and Modules”</strong>, Proc. of the 21st European Photovoltaic Solar Energy Conference, (Dresden, Germany, 2006), p315.</li> - - <li class="pub">A J Chatten, D J Farrell, B F Buxton, A Büchtemann and K W J Barnham, <strong>“Thermodynamic Modelling of Luminescent Solar Concentrators and Modules”</strong>, Proc. of the 21st European Photovoltaic Solar Energy Conference, (Dresden, Germany, 2006), p315.</li> - - <li class="pub">L H Slooff, R Kinderman, A R Burgers, J A M van Roosmalen, A Büchtemann, A J Chatten, D J Farrell and K W J Barnham, <strong>“The luminescent concentrator: a bright idea for spectrum conversion?”</strong>, Proc. of the 20th European Photovoltaic Solar Energy Conference, (Barcelona, Spain, 2005), p413.</li> - - <li class="pub">A J Chatten, D J Farrell, C Jermyn, P Thomas, B F Buxton, A Büchtemann, R Danz, and K W J Barnham, <strong>“Thermodynamic Modelling of Luminescent Solar Concentrators”</strong>, Proc. 31st IEEE Photovoltaic Specialists Conference, (Orlando, USA, 2005), p82.</li> - - </ul> - <h5>Books & chapters</h5> - <ul class="publist"> - - <li class="pub"><strong>"New Research on Astrophysics, Neutron Stars and Galaxy Clusters edited by Louis V. Ross"</strong>, J. Dunning-Davies and D J Farrell, <strong>"Universal Constants and Black Holes"</strong>, p.67-85, ISBN1-59033-784-0 (2003).</li> - - </ul> - - <h5>Presentations</h5> - <ul class="publist"> - <li class="pub"><strong>“Fabrication, Characterisation and Modelling of Quantum Dot Solar Concentrator Stacks”</strong>, IEEE 4th World Conference on Photovoltaic Energy Conversion, (Waikoloa, Hawaii, 2006).</li> - </ul> - <h5>Poster presentations</h5> - <ul class="publist"> - <li class="pub"><strong>"Thermodynamic modelling of the Luminescent Solar Concentrator"</strong>, PVNet-3 UK Conference (Loughborough, UK, 2005)</li> - <li class="pub"><strong>“The Luminescent Concentrator: Large Area Modelling And Results With Dye Based Stack Concentrators And Thin-Film Composite Plates”</strong>, Proc. of the 20th European Photovoltaic Solar Energy Conference, (Barcelona, Spain, 2005)</li> - </ul> - <h5>Invited talks</h5> - <ul class="publist"> - <li class="pub"><strong>“The next generation of Building Integrated Photovoltaics”</strong>, Arup, London May 2009.</li> - </ul> - </div> - </div> - <hr> - <p class="light">Updated: 5th July 2009</p> - </div> - -</body> -</html> \ No newline at end of file diff --git a/research/index.html b/research/index.html new file mode 100644 index 0000000..c7709e3 --- /dev/null +++ b/research/index.html @@ -0,0 +1,86 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> + +<html lang="en"> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London" /> + <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated" /> + <meta name="author" content="Daniel J Farrell" /> + <title>Daniel J Farrell</title> + + <!-- Framework CSS --> + <link rel="stylesheet" href="../blueprint/screen.css" type="text/css" media="screen, projection"> + <link rel="stylesheet" href="../blueprint/print.css" type="text/css" media="print"> + <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> + + <!-- Import fancy-type plugin --> + <link rel="stylesheet" href="../blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> + + <link rel="stylesheet" href="../blueprint/plugins/navigation/sliding.css" type="text/css" media="screen, projection" /> + +</head> + +<body> + + <hr class="space"> + <hr class="space"> + <hr class="space"> + <hr class="space"> + + + <div class="container"> + + + <div class="span-6"> + <h1 class="light">Daniel J Farrell</h1> + </div> + + <div class="push-1 span-13"> + <ul class="green"> + <li class="green"><a href="../index.html" title="home" ><span>home</span></a></li> + <li class="green"><a href="index.html" title="research" class="current"><span>research</span></a></li> + <li class="green"><a href="../freebies/index.html" title="freebies"><span>freebies</span></a></li> + <li class="green" ><a href="../contact/index.html" title="contact"><span>contact</span></a></li> + </ul> + </div> + + <hr class="space"> + + <div class="span-6"> + <img src="imdaniel_j_farrell.jpg" class="top push-0 shadow" alt="test" width="240px"> + </div> + + <div class="span-6 push-1 colborder"> + <h6>About</h6> + <p>Daniel is presently a post doctoral researcher in the Experimental Solid State Physics group at Imperial College London. His research activities revolve around approaches to increase the efficiency and reduce the cost of solar energy conversion and include: hot-carrier solar cells and spectral modification with luminescent materials.</p> + </div> + + <p> + <h3><span class="alt">Follow me here...</span></h3> + <a href="http://twitter.com/danieljfarrell"> <img src="../img/twitter.jpg" width="35"/></a> + <a href="http://linkedin.com/in/danieljfarrell"> <img src="../img/linkedin.jpg" width="33"/></a> + <a href="http://www.mendeley.com/profiles/daniel-farrell/"><img border="0" src="http://www.mendeley.com/embed/icon/1/blue/small" alt="Daniel Farrell's bibliography"/></a> + </p> + + + <div class="span-13 last"> + <hr> + <h3 class=""> Recent publications and talks</h3> + <ul class="publist"> + <li class="pub">D J Farrell and N J Ekins-Daukes, <em>"Photovoltaic technology: Relay dye boosts efficiency"</em>, <strong>Nature Photonics</strong>, 2009, 3: 373 - 374. <a href="http://doi:10.1038/nphoton.2009.108">doi:10.1038/nphoton.2009.108 +</a></li> + <li class="pub">D J Farrell, W G J H M van Sark, S T Velthuijsen and R E I Schropp, R, 2010, <em>"Using amorphous silicon solar cells to boost the viability of luminescent solar concentrators"</em>. <strong>Physica Status Solidi (c)</strong>, 7: 1045–1048. <a href="http://dx.doi.org/10.1002/pssc.200982866">doi:10.1002/pssc.200982866</a></li> + + <li class="publist"> + D J Farrell, <em>The next generation of Building Integrated Photovoltaics.</em>", presented to <a class="loud" href="http://www.arup.com">Arup Associates</a>, London 2009. + </li> + </ul> + </div> + + + + </div> + +</body> +</html>
danieljfarrell/website-2.0
48bbc4548c9f64fb47b4da33b48e301888233f89
Content updated, not finished.
diff --git a/keith/._index.html b/blueprint/.DS_Store old mode 100755 new mode 100644 similarity index 59% rename from keith/._index.html rename to blueprint/.DS_Store index ce58499..dafd66d Binary files a/keith/._index.html and b/blueprint/.DS_Store differ diff --git a/blueprint/plugins/.DS_Store b/blueprint/plugins/.DS_Store new file mode 100644 index 0000000..c4831de Binary files /dev/null and b/blueprint/plugins/.DS_Store differ diff --git a/img/.DS_Store b/img/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/img/.DS_Store differ diff --git a/img/IC.png b/img/IC.png new file mode 100644 index 0000000..a812975 Binary files /dev/null and b/img/IC.png differ diff --git a/QDCs.png b/img/QDCs.png similarity index 100% rename from QDCs.png rename to img/QDCs.png diff --git a/col.jpg b/img/col.jpg similarity index 100% rename from col.jpg rename to img/col.jpg diff --git a/col.png b/img/col.png similarity index 100% rename from col.png rename to img/col.png diff --git a/daniel_j_farrell.jpg b/img/daniel_j_farrell.jpg similarity index 100% rename from daniel_j_farrell.jpg rename to img/daniel_j_farrell.jpg diff --git a/daniel_j_farrell_square.jpg b/img/daniel_j_farrell_square.jpg similarity index 100% rename from daniel_j_farrell_square.jpg rename to img/daniel_j_farrell_square.jpg diff --git a/img/diagrams.key b/img/diagrams.key new file mode 100644 index 0000000..935c17e Binary files /dev/null and b/img/diagrams.key differ diff --git a/img/diagrams.pdf b/img/diagrams.pdf new file mode 100644 index 0000000..6d88a58 Binary files /dev/null and b/img/diagrams.pdf differ diff --git a/img/linkedin.jpg b/img/linkedin.jpg new file mode 100644 index 0000000..d9fdcc5 Binary files /dev/null and b/img/linkedin.jpg differ diff --git a/img/losses.jpg b/img/losses.jpg new file mode 100644 index 0000000..fab65a1 Binary files /dev/null and b/img/losses.jpg differ diff --git a/lsc.jpg b/img/lsc.jpg similarity index 100% rename from lsc.jpg rename to img/lsc.jpg diff --git a/img/twitter.jpg b/img/twitter.jpg new file mode 100644 index 0000000..cfca4b0 Binary files /dev/null and b/img/twitter.jpg differ diff --git a/index copy.html b/index copy.html deleted file mode 100755 index 1689f38..0000000 --- a/index copy.html +++ /dev/null @@ -1,141 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" - "http://www.w3.org/TR/html4/strict.dtd"> - -<html lang="en"> -<head> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> - <meta name="microid" content="mailto+http:sha1:d88ae819ad27750216a14d0338bdd81fb38d2a9a" /> - <link rel="openid.server" href="http://openid.claimid.com/server" /> - <link rel="openid.delegate" href="http://openid.claimid.com/boyfarrell" /> - <title>Daniel J Farrell</title> - - <!-- Framework CSS --> - <link rel="stylesheet" href="blueprint/screen.css" type="text/css" media="screen, projection"> - <link rel="stylesheet" href="blueprint/print.css" type="text/css" media="print"> - <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> - - <!-- Import fancy-type plugin for the sample page. --> - <link rel="stylesheet" href="blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> -</head> - -<body> - - <div class="container"> - <h1 class="light">Daniel J Farrell</h1> - <hr/> - <!-- <h2 class="alt">Research Associate in quantum photovoltaics at Imperial College London</h2> --> - <h2 class="alt">Research student in the Quantum Photovoltaics Group at Imperial College London</h2> - <hr> - - <div class="span-6 colborder"> - <h6>About</h6> - I am in the final stages of completing my PhD under the supervision of Prof. Keith Barnham on the 'Characterisation, modelling and development of Luminescent Solar Concentrators'. I will continue to work on Luminescent Concentrators and Quantum Dots in the group at Imperial College over the coming months. <!--I have completed extensive experimental and computational work on wave-guide structures and am currently investigating optical thin-films. I other areas I have advised a large multinational on commercialisation of a building integrate photovoltaic product. --> - <!--Photovoltaics (PV) is the science of electrical power generation by the direct conversion of solar energy. In our research group we are looking a new material and have pioneered the use of nano-structures to make solar energy cheaper.!--> - </div> - - <div class="span-6 colborder"> - <h6>Research Interests</h6> - <ul> - <li>Photovoltaic cells</li> - <li>Luminescent concentrators</li> - <li>Nano-materials: - <ul class="nest-2"><li>Quantum dots and rod</li> - <li>Organic dyes</li> - </ul> - <li>Building integrated photovoltaics</li> - <li>Thin-film optical coatings - <li>Thermodynamics of dissipative structures</li> - <li>Computer modelling</li> - </ul> - </div> - - <div class="span-5 last"> - <h6>Contact</h6> - <p>Mr. Daniel J Farrell<br> - Experimental Solid State Physics<br> - Blackett Laboratory,<br> - Imperial College London,<br> - Prince Consort Road,<br> - London SW7 2AZ.<br> - U.K. <br> - e-mail: <a href="mailto:[email protected]">[email protected]</a><br> - tel: (+44) - (0)20 7995 6678 - </p> - </div> - <hr> - <hr class="space"> - - <div class="span-13 append-5 colborder"> - <p> - <img src="lsc.jpg" class="top push-0" alt="test"> - <div class="pcaption"> - <p>Luminescent concentrators being illuminated by an uniform light source (conveniently provided by a laptop screen).</p></div> - <h5>Luminescent concentrators</h5> - <p>The luminescent concentrator is a non-tracking approach to the concentration of solar energy. One very important feature of the luminescent concentrator is that it collects diffuse light as well as direct. This is significant, especially for high latitudes where the diffuse can account for 60% of the total insolation. The luminescent concentrator aims to reduced the cost-per-watt of generated power. This is achieved by the geometric and photon concentration factors between the top and edge surfaces.</p> - - <h5>Quantum Dots</h5> - <p>Quantum dots are nanoscale crystals of semiconductor materials. One interesting feature of quantum dots is that their optical properties are size dependent. This is because of <em>quantum confinement</em> of the electron and hole wavefunctions. Our group has proposed replacing organic dyes with quantum dots in luminescent concentrators. This has several advantages; emission colour can be changed by changing the particle size, large red-shifts can be produced by controlling the spread in dot sizes and quantum dots should be inherently more stable than organic materials.</p> - <p>Quantum dots also form the basis of many 3rd generation photovoltaics concepts such as; the intermediate band solar and hot carrier solar cells.</p> - <hr> - <div class="span-13 last"> - <h5>Publications</h5> - <ul class="publist"> - <li class="pub">D J Farrell, A J Chatten, A Büchtemann and K W J Barnham, <strong>“Fabrication, Characterisation and Modelling of Quantum Dot Solar Concentrator Stacks”</strong>, Proc. IEEE 4th World Conference on Photovoltaic Energy Conversion, (Waikoloa, Hawaii, 2006), p217.</li> - - <li class="pub">D J Farrell, A J Chatten, B F Buxton, A Büchtemann, R Danz, M Schleusener, L H Slooff, R Kinderman, A R Burgers, J A M van Roosmalen and K W J Barnham, <strong>“The Luminescent Concentrator: Large Area Modelling And Results With Dye Based Stack Concentrators And Thin-Film Composite Plates”</strong>, Proc. of the 20th European Photovoltaic Solar Energy Conference, (Barcelona, Spain, 2005), p386.</li> - - <li class="pub">D J Farrell, A J Chatten, B F Buxton and K W J Barnham, <strong>"Thermodynamic modelling of the Luminescent Solar Concentrator"</strong>, PVNet-3 UK Conference (Loughborough, UK, 2005).</li> - - </ul> - - <h5>Collaborative publications</h5> - <ul class="publist"> - <li class="pub">R Bose, D J Farrell, A J Chatten, A Büchtemann and K W J Barnham, <strong>“Luminescent Solar Concentrators”</strong>, Proc. Photovoltaic Science Applications and Technology (PVSAT-3), (Durham, UK, 2007), p63.</li> - - <li class="pub">A J Chatten D J Farrell, R Bose, M G Debije, A Büchtemann and K W J Barnham, <strong>“Thermodynamic Modelling of Luminescent Solar Concentrators with Reduced Top Surface Losses”</strong>, abstract accepted: 22nd European Photovoltaic Solar Energy Conference, (Milan, Italy, 2007).</li> - - <li class="pub">A J Chatten, D J Farrell, B F Buxton, A Büchtemann and K W J Barnham, <strong>“Thermodynamic Modelling of Luminescent Solar Concentrators and Modules”</strong>, Proc. of the 21st European Photovoltaic Solar Energy Conference, (Dresden, Germany, 2006), p315.</li> - - <li class="pub">A J Chatten, D J Farrell, B F Buxton, A Büchtemann and K W J Barnham, <strong>“Thermodynamic Modelling of Luminescent Solar Concentrators and Modules”</strong>, Proc. of the 21st European Photovoltaic Solar Energy Conference, (Dresden, Germany, 2006), p315.</li> - - <li class="pub">L H Slooff, R Kinderman, A R Burgers, J A M van Roosmalen, A Büchtemann, A J Chatten, D J Farrell and K W J Barnham, <strong>“The luminescent concentrator: a bright idea for spectrum conversion?”</strong>, Proc. of the 20th European Photovoltaic Solar Energy Conference, (Barcelona, Spain, 2005), p413.</li> - - <li class="pub">A J Chatten, D J Farrell, C Jermyn, P Thomas, B F Buxton, A Büchtemann, R Danz, and K W J Barnham, <strong>“Thermodynamic Modelling of Luminescent Solar Concentrators”</strong>, Proc. 31st IEEE Photovoltaic Specialists Conference, (Orlando, USA, 2005), p82.</li> - - </ul> - <h5>Books & chapters</h5> - <ul class="publist"> - - <li class="pub"><strong>"New Research on Astrophysics, Neutron Stars and Galaxy Clusters edited by Louis V. Ross"</strong>, J. Dunning-Davies and D J Farrell, <strong>"Universal Constants and Black Holes"</strong>, p.67-85, ISBN1-59033-784-0 (2003).</li> - - </ul> - - <h5>Presentations</h5> - <ul class="publist"> - <li class="pub"><strong>“Fabrication, Characterisation and Modelling of Quantum Dot Solar Concentrator Stacks”</strong>, IEEE 4th World Conference on Photovoltaic Energy Conversion, (Waikoloa, Hawaii, 2006).</li> - </ul> - <h5>Poster presentations</h5> - <ul class="publist"> - <li class="pub"><strong>"Thermodynamic modelling of the Luminescent Solar Concentrator"</strong>, PVNet-3 UK Conference (Loughborough, UK, 2005)</li> - <li class="pub"><strong>“The Luminescent Concentrator: Large Area Modelling And Results With Dye Based Stack Concentrators And Thin-Film Composite Plates”</strong>, Proc. of the 20th European Photovoltaic Solar Energy Conference, (Barcelona, Spain, 2005)</li> - </ul> - </div> - </div> - <div class="span-6 last"> - <h3><span class="alt">My links</span></h3> - <p> - <a href="http://www.sc.ic.ac.uk/~q_pv/">Quantum photovoltaics group</a> - <a href="http://www.linkedin.com/in/danieljfarrell">linkedin.com/in/danieljfarrell</a> - <a href="http://identi.ca/danieljfarrell">http://identi.ca/danieljfarrell</a> - </p> - - <h3><span class="alt">My bookmarks</span></h3> - <p><script type="text/javascript" src="http://del.icio.us/feeds/js/boyfarrell?;count=15"></script></p> - - </div> - <hr> - <p class="light">Updated: 22th September 2008</p> - </div> - -</body> -</html> \ No newline at end of file diff --git a/index.html b/index.html index 0a92e90..7dfc55e 100644 --- a/index.html +++ b/index.html @@ -1,134 +1,168 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> - <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London" /> - <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated" /> - <meta name="author" content="Daniel J Farrell" /> - <meta name="microid" content="mailto+http:sha1:ab095e627455a292fb5fd60550b0fa4a2105ae79" /> - <link rel="openid.server" href="http://openid.claimid.com/server" /> - <link rel="openid.delegate" href="http://daniel.farrell.name" /> - <title>Daniel J Farrell</title> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London" /> + <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated" /> + <meta name="author" content="Daniel J Farrell" /> + <meta name="microid" content="mailto+http:sha1:ab095e627455a292fb5fd60550b0fa4a2105ae79" /> + <link rel="openid.server" href="http://openid.claimid.com/server" /> + <link rel="openid.delegate" href="http://daniel.farrell.name" /> + <title>Daniel J Farrell</title> <!-- Framework CSS --> - <link rel="stylesheet" href="blueprint/screen.css" type="text/css" media="screen, projection"> - <link rel="stylesheet" href="blueprint/print.css" type="text/css" media="print"> + <link rel="stylesheet" href="blueprint/screen.css" type="text/css" media="screen, projection"> + <link rel="stylesheet" href="blueprint/print.css" type="text/css" media="print"> <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> - - <!-- Import fancy-type plugin for the sample page. --> - <link rel="stylesheet" href="blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> + + <!-- Import fancy-type plugin for the sample page. --> + <link rel="stylesheet" href="blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> </head> <body> + + <div class="container"> + <div class="span-6"> + <h1 class="light">Daniel J Farrell</h1> + </div> + - <div class="container"> - <div class="span-6 colborder"> - <h1 class="light">Daniel J Farrell</h1> - <hr class="space"> - <img src="daniel_j_farrell.jpg" class="top push-0 shadow" alt="test" width="240px"> - </div> - - <h2 class="alt">Research Associate in the <a href="http://www.imperial.ac.uk/qpv">Quantum Photovoltaics Group</a> at Imperial College London</h2> - <p> </p> - <img src="col.png" class="top push-0 shadow" alt="test" width="525px"> + + <!-- <h2 class="alt">Research Associate in quantum photovoltaics at Imperial College London</h2> --> + + <hr class="space"> + + + <div class="span-6"> + <img src="daniel_j_farrell.jpg" class="top push-0 shadow" alt="test" width="240px"> + </div> + + <div class="span-6 push-1 colborder"> + <h6>About</h6> + <p>Daniel is presently a post doctoral researcher in the Experimental Solid State Physics group at Imperial College London. His research activities revolve around approaches to increase the efficiency and reduce the cost of solar energy conversion and include: hot-carrier solar cells and spectral modification with luminescent materials.</p> - - <!-- <h2 class="alt">Research Associate in quantum photovoltaics at Imperial College London</h2> --> - - <hr class="space"> - <hr> - - - <div class="span-6 colborder"> - <h6>About</h6> - <p>I am a post doctoral researcher in the Experimental Solid State Physics group at Imperial College London, where I research hot-carrier solar cells, thermodynamics of solar energy conversion and spectral modification with luminescent materials.</p> - - <!--I am in the final stages of completing my PhD under the supervision of Prof. Keith Barnham on the 'Characterisation, modelling and development of Luminescent Solar Concentrators'. I will continue to work on Luminescent Concentrators and Quantum Dots in the group at Imperial College over the coming months.--> <!--I have completed extensive experimental and computational work on wave-guide structures and am currently investigating optical thin-films. I other areas I have advised a large multinational on commercialisation of a building integrate photovoltaic product. --> - <!--Photovoltaics (PV) is the science of electrical power generation by the direct conversion of solar energy. In our research group we are looking a new material and have pioneered the use of nano-structures to make solar energy cheaper.!--> - </div> - - <div class="span-6 colborder"> - <h6>Research Interests</h6> - <ul> - <li>Hot-carrier solar cells</li> - <li>Thermodynamic modelling of solar energy convertors</li> - <li>Luminescent solar concentrators</li> - <li>Nano-materials: - <ul class="nest-2"><li>Quantum dots and rods</li> - <li>Organic dyes</li> - </ul> - <li>Building integrated photovoltaics</li> - <li>Thin-film optical coatings</li> - <li>Monte-Carlo optical modelling</li> - </ul> - </div> - - <div class="span-5 last"> - <h6>Contact</h6> - <p>Dr. Daniel J Farrell<br> - Experimental Solid State Physics<br> - Blackett Laboratory,<br> - Imperial College London,<br> - Prince Consort Road,<br> - London SW7 2AZ.<br> - U.K. <br> - e-mail: <a href="mailto:[email protected]">[email protected]</a><br> - tel: (+44) - (0)20 7594 7305 - </p> - </div> - <hr> - - <div class="span-13 append-5 colborder"> - <p> - <h5>Hot-carrier solar cell</h5> - <!--<p>When sunlight is absorbed by a solar cell, the energy distribution of electrons promoted to the conduction band (and also holes in the valence band) is coherent with the incident spectrum. However, the coherency is rapidly lost (on the scale of femtoseconds) as electron-electron scattering brings the carriers into a thermal distribution with each other. This is known as the hot-carrier phase, because the characteristic temperature is much hotter than the lattice temperature. The electrons are in thermal equilibrium with each other but are not in thermal equilibrium with the lattice. The hot-carrier will steadily cool (in the order of picoseconds) to a thermal distribution characterised by the lattice temperature and a non-zero quasi-fermi level.</p>--> - -<p>Within the framework of the hot-carrier solar cell, thermalisation losses are eliminated by forbidding interactions between charge carriers and the lattice. Energy that would otherwise be lost is stored in the carrier population as heat. Provided that the carriers are thermally isolated from the lattice they may attain a temperature intermediate between that of the Sun and the ambient, and extra energy can be extracted because entropy generation is suppressed.</p> - - <h5>Luminescent concentrators</h5> - - <img src="lsc.jpg" class="top push-0 shadow" alt="test"> - <div class="pcaption"> - <p>Luminescent concentrators being illuminated by an uniform light source (conveniently provided by a laptop screen).</p></div> - - <p>The luminescent concentrator is a non-tracking approach to the concentration of solar energy. One very important feature of the luminescent concentrator is that it collects diffuse light as well as direct. This is significant, especially for high latitudes where the diffuse can account for 60% of the total insolation. The luminescent concentrator aims to reduced the cost-per-watt of generated power. This is achieved by the geometric and photon concentration factors between the top and edge surfaces.</p> - - <h5>Quantum Dots</h5> - <p>Quantum dots are nanoscale crystals of semiconductor materials. One interesting feature of quantum dots is that their optical properties are size dependent. This is because of <em>quantum confinement</em> of the electron and hole wavefunctions. Our group has proposed replacing organic dyes with quantum dots in luminescent concentrators. This has several advantages; emission colour can be changed by changing the particle size, large red-shifts can be produced by controlling the spread in dot sizes and quantum dots should be inherently more stable than organic materials.</p> - <hr> - <div class="span-13 last"> - <h5> Recent publications and talks</h5> - <ul class="publist"> - <li class="pub">D J Farrell and N J Ekins-Daukes, <strong>"Photovoltaic technology: Relay dye boosts efficiency"</strong>, <a href="http://dx.doi.org/10.1038/nphoton.2009.108">Nature Photonics 3, 373 - 374 (2009) </a></li> - <li class="pub">D J Farrell, Wilfried G J H M van Sark, S T Velthuijsen, R E I Schropp, <strong>Using amorphous silicon solar cells to boost the viability of Luminescent Solar Concentrators</strong>, <a href="http://www.icans23.org">23rd International Conference on Amorphous and Nanocrystalline Semiconductors</a>, August 2009 (<a href="publications/farrell-icans23.pdf">Download Pre-print</a>).</li> - - <li class="publist"> - D J Farrell, <strong>"<a href="publications/arup.html">The next generation of Building Integrated Photovoltaics</a>"</strong>, <a href="http://www.arup.com">Arup Associates</a>, London, (2009). - </li> - <li> - <a href="publications/index.html">Full publication list.</a> - </li> - </ul> - </div> - </div> + </div> + + <!-- + <div class="span-6 colborder"> + <h6>Research Interests</h6> + <ul> + <li>Hot-carrier solar cells</li> + <li>Thermodynamic modelling of solar energy convertors</li> + <li>Luminescent solar concentrators</li> + <li>Nano-materials: + <ul class="nest-2"><li>Quantum dots and rods</li> + <li>Organic dyes</li> + </ul> + <li>Building integrated photovoltaics</li> + <li>Thin-film optical coatings</li> + <li>Monte-Carlo optical modelling</li> + </ul> + </div> + --> + + <div class="span-5 last"> + <h6>Contact</h6> + <p>Dr. Daniel J Farrell<br> + Experimental Solid State Physics<br> + Blackett Laboratory,<br> + Imperial College London,<br> + Prince Consort Road,<br> + London SW7 2AZ.<br> + U.K. <br> + e-mail: <a href="mailto:[email protected]">[email protected]</a><br> + tel: (+44) - (0)20 7594 7305 + </p> + </div> + <hr> + + <div class="span-13 append-5 colborder"> + + <h1 class="alt"> Research</h1> + + <h3>The efficiency challenge</h3> + + <div style="float: right;" class="push-1 span-5"> + <h3 class="alt"><span class="dquo">&#8220;</span>The challenge for future research is to better harness the energy content of each photon.&#8221;</h3> + </div> + + <p> + Conventional solar cell are now, after many decades of research and development, beginning to approach their fundamental limits. These devices harvest <em>solar photons</em> and directly convert them to electrical current.</p> + + <div class"align-right"> + <img src="img/losses.jpg" width="410" alt="Fundamental losses in solar cells: thermalisation loss and below bandgap loss."/> + <p class="pcaption">Fundamental losses in solar cells: thermalisation loss and below bandgap loss.</p> + </div> + + <p>A spectrum of photons enter conventional solar cells: blue and UV photons possess high energy and red and infrared photons possess less energy. A semiconductor has an energy threshold that called the <em>bandgap</em> that is the minimum energy a photon needs to be absorbed. If a photon has less energy it will remain unabsorbed; from the perspective of the photon the material looks transparent. This is called <em>below bandgap loss</em>.</p> + + <p> + When electrons exit a solar cell they all eave with the same amount of energy (set by the voltage of device). However, light that generated these electrons has a large range of energies, thus during the conversion process energy has been lost. This is known as <em>thermalisation loss</em>. In conventional solar cells the energy of above bandgap photons is not utilised, it simply wasted as lattice vibrations (heat).</p> + + <div> + <img src="http://chart.apis.google.com/chart?chxs=0,676767,16&chxt=x&chs=410x150&cht=p3&chco=B4C7AB|C2CEE4|9B8A9D|3366CC&chd=s:TVV&chdl=Power|Thermalisation|Unabsorbed&chl=31%25|34%25|35%25" width="410" height="150" alt="" /> + <p class="pcaption">Where does the energy go?</p> + </div> + + <p>In today's best solar cells the power extracted is less than 1/3 of the solar power that was incident. The pie chart show how the absorbed energy divides up into useful power generation, and the losses processes.</p> + <p> + The challenge for future research is to better harness the energy content of each photon. Moreover, rather than just capturing solar photons in a one-to-one conversion process we must address how the <em>solar energy</em> carried by each photon can be utilised to the fullest potential.</p> + + <h3>Hot-carrier solar cells</h3> + + <p>The hot-carrier solar cell is one of the most ambitious attempts at making the ultimate photovoltaic converter. It has the potential to eliminate both thermalisation and below bandgap losses. In this concept, thermalisation losses are eliminated using a mechanism prevents charge carriers from interacting with the lattice. Energy that would otherwise transfer to the lattice is stored in the carrier population as heat. In theory this enables very high conversion efficiencies because a low bandgap material can be chosen to maximise absorption across the spectrum, and still achieve high efficiency.</p> + + <h5>Luminescent solar concentrators</h5> + + <p>As well as being efficiency, the other factor driving photovoltaic research is the reduction of costs. High efficiency approaches are best suited to large power-plant installation. What is important for the average consumer or small business wishing to install solar panels is the <em>cost-per-Watt</em> of the technology: how much power power is generated for the amount of money spent.</p> + + <img src="img/lsc.jpg" class="top push-0 shadow" alt="Luminescent solar concentrators"> + <div class="pcaption"> + <p>Luminescent solar concentrators.</p></div> + + <p>The luminescent concentrator is a non-tracking approach to the concentration of solar energy. One very important feature of the luminescent concentrator is that it collects diffuse light as well as direct. This is significant, especially for high latitudes where the diffuse can account for 60% of the total insolation. The luminescent concentrator aims to reduced the cost-per-watt of generated power. This is achieved by the geometric and photon concentration factors between the top and edge surfaces.</p> + + <h5>Quantum Dots</h5> + <p>Quantum dots are nanoscale crystals of semiconductor materials. One interesting feature of quantum dots is that their optical properties are size dependent. This is because of <em>quantum confinement</em> of the electron and hole wavefunctions. Our group has proposed replacing organic dyes with quantum dots in luminescent concentrators. This has several advantages; emission colour can be changed by changing the particle size, large red-shifts can be produced by controlling the spread in dot sizes and quantum dots should be inherently more stable than organic materials.</p> + <hr> + <div class="span-13 last"> + <h5> Recent publications and talks</h5> + <ul class="publist"> + <li class="pub">D J Farrell and N J Ekins-Daukes, <strong>"Photovoltaic technology: Relay dye boosts efficiency"</strong>, <a href="http://dx.doi.org/10.1038/nphoton.2009.108">Nature Photonics 3, 373 - 374 (2009) </a></li> + <li class="pub">D J Farrell, Wilfried G J H M van Sark, S T Velthuijsen, R E I Schropp, <strong>Using amorphous silicon solar cells to boost the viability of Luminescent Solar Concentrators</strong>, <a href="http://www.icans23.org">23rd International Conference on Amorphous and Nanocrystalline Semiconductors</a>, August 2009 (<a href="publications/farrell-icans23.pdf">Download Pre-print</a>).</li> + + <li class="publist"> + D J Farrell, <strong>"<a href="publications/arup.html">The next generation of Building Integrated Photovoltaics</a>"</strong>, <a href="http://www.arup.com">Arup Associates</a>, London, (2009). + </li> + <li> + <a href="publications/index.html">Full publication list.</a> + </li> + </ul> + </div> + </div> <div class="span-6 last"> - <h3><span class="alt">Follow me here...</span></h3> - <p> - <a href="http://www.imperial.ac.uk/qpv">Quantum photovoltaics group</a> - <a href="http://www.linkedin.com/in/danieljfarrell">linkedin.com/in/danieljfarrell</a> - <a href="http://identi.ca/danieljfarrell">http://identi.ca/danieljfarrell</a> - <a href="http://twitter.com/danieljfarrell">http://twitter.com/danieljfarrell</a> - </p> - - <h3><span class="alt">My bookmarks</span></h3> - <p><script type="text/javascript" src="http://feeds.delicious.com/v2/js/boyfarrell?title=&icon=m&count=15&sort=date&extended"></script></p> + <p> + <h3><span class="alt">Follow me here...</span></h3> + <a href="http://twitter.com/danieljfarrell"> <img src="img/twitter.jpg" width="35"/></a> + <a href="http://linkedin.com/in/danieljfarrell"> <img src="img/linkedin.jpg" width="33"/></a> + <a href="http://www.mendeley.com/profiles/daniel-farrell/"><img border="0" src="http://www.mendeley.com/embed/icon/1/blue/small" alt="Daniel Farrell's bibliography"/></a> + </p> + <hr class="space"> + <p> + <h3><span class="alt">Imperial College London</span></h3> + <a href="http://www.imperial.ac.uk/qpv">Quantum Photovoltaics Group</a> + </p> + <hr class="space"> + <p> + <h3><span class="alt">My bookmarks</span></h3> + <script type="text/javascript" src="http://feeds.delicious.com/v2/js/boyfarrell?title=&icon=m&count=15&sort=date&extended"></script></p> - </div> - <hr> - <p class="light">Updated: 5th July 2009</p> - </div> + </div> + <hr> + <p class="light">Updated: 5th July 2009</p> + </div> </body> </html> diff --git a/keith/1.JPG b/keith/1.JPG deleted file mode 100755 index 7d8d933..0000000 Binary files a/keith/1.JPG and /dev/null differ diff --git a/keith/2.JPG b/keith/2.JPG deleted file mode 100755 index 01a551c..0000000 Binary files a/keith/2.JPG and /dev/null differ diff --git a/keith/3.JPG b/keith/3.JPG deleted file mode 100755 index 961429c..0000000 Binary files a/keith/3.JPG and /dev/null differ diff --git a/keith/4.JPG b/keith/4.JPG deleted file mode 100755 index 6d02120..0000000 Binary files a/keith/4.JPG and /dev/null differ diff --git a/keith/5.JPG b/keith/5.JPG deleted file mode 100755 index 0e9263d..0000000 Binary files a/keith/5.JPG and /dev/null differ diff --git a/keith/index.html b/keith/index.html deleted file mode 100755 index b1a2ceb..0000000 --- a/keith/index.html +++ /dev/null @@ -1,32 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" - "http://www.w3.org/TR/html4/strict.dtd"> - -<html lang="en"> -<head> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> - <title>http://homepage.mac.com/danieljfarrell/keith/</title> - - <!-- Framework CSS --> - <link rel="stylesheet" href="../blueprint/screen.css" type="text/css" media="screen, projection"> - <link rel="stylesheet" href="../blueprint/print.css" type="text/css" media="print"> - <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> - - <!-- Import fancy-type plugin for the sample page. --> - <link rel="stylesheet" href="blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> -</head> - -<body> - - <div class="container"> - <h1 class="light">Stained class windows</h1> - <hr/> - <ul> - <li><a href="http://homepage.mac.com/danieljfarrell/keith/1.JPG">http://homepage.mac.com/danieljfarrell/keith/1.JPG</a></li> - <li><a href="http://homepage.mac.com/danieljfarrell/keith/2.JPG">http://homepage.mac.com/danieljfarrell/keith/2.JPG</a></li> - <li><a href="http://homepage.mac.com/danieljfarrell/keith/3.JPG">http://homepage.mac.com/danieljfarrell/keith/3.JPG</a></li> - <li><a href="http://homepage.mac.com/danieljfarrell/keith/4.JPG">http://homepage.mac.com/danieljfarrell/keith/4.JPG</a></li> - <li><a href="http://homepage.mac.com/danieljfarrell/keith/5.JPG">http://homepage.mac.com/danieljfarrell/keith/5.JPG</a></li> - </div> - -</body> -</html> \ No newline at end of file
danieljfarrell/website-2.0
f04db96df14de99d2d34b8d7ceb9f9089aa7d06b
daniel.farrell.name website 9/8/2010
diff --git a/QDCs.png b/QDCs.png new file mode 100755 index 0000000..6397446 Binary files /dev/null and b/QDCs.png differ diff --git a/blueprint/ie.css b/blueprint/ie.css new file mode 100755 index 0000000..bb59a79 --- /dev/null +++ b/blueprint/ie.css @@ -0,0 +1,22 @@ +/* ----------------------------------------------------------------------- + + Blueprint CSS Framework 0.7.1 + http://blueprintcss.googlecode.com + + * Copyright (c) 2007-2008. See LICENSE for more info. + * See README for instructions on how to use Blueprint. + * For credits and origins, see AUTHORS. + * This is a compressed file. See the sources in the 'src' directory. + +----------------------------------------------------------------------- */ + +/* ie.css */ +body {text-align:center;} +.container {text-align:left;} +* html .column {overflow-x:hidden;} +* html legend {margin:-18px -8px 16px 0;padding:0;} +ol {margin-left:2em;} +sup {vertical-align:text-top;} +sub {vertical-align:text-bottom;} +html>body p code {*white-space:normal;} +hr {margin:-8px auto 11px;} \ No newline at end of file diff --git a/blueprint/plugins/fancy-type/screen.css b/blueprint/plugins/fancy-type/screen.css new file mode 100644 index 0000000..735641e --- /dev/null +++ b/blueprint/plugins/fancy-type/screen.css @@ -0,0 +1,75 @@ +/* -------------------------------------------------------------- + + fancy-type.css + * Lots of pretty advanced classes for manipulating text. + + See the Readme file in this folder for additional instructions. + +-------------------------------------------------------------- */ + +/* Indentation instead of line shifts for sibling paragraphs. */ + p + p { text-indent:2em; margin-top:-1.5em; } + form p + p { text-indent: 0; } /* Don't want this in forms. */ + + +/* For great looking type, use this code instead of asdf: + <span class="alt">asdf</span> + Best used on prepositions and ampersands. */ + +.alt { + color: #666; + font-family: "Warnock Pro", "Goudy Old Style","Palatino","Book Antiqua", Georgia, serif; + font-style: italic; + font-weight: normal; +} + +.light { + font-weight:lighter; +} + + +/* For great looking quote marks in titles, replace "asdf" with: + <span class="dquo">&#8220;</span>asdf&#8221; + (That is, when the title starts with a quote mark). + (You may have to change this value depending on your font size). */ + +.dquo { margin-left: -.5em; } + + +/* Reduced size type with incremental leading + (http://www.markboulton.co.uk/journal/comments/incremental_leading/) + + This could be used for side notes. For smaller type, you don't necessarily want to + follow the 1.5x vertical rhythm -- the line-height is too much. + + Using this class, it reduces your font size and line-height so that for + every four lines of normal sized type, there is five lines of the sidenote. eg: + + New type size in em's: + 10px (wanted side note size) / 12px (existing base size) = 0.8333 (new type size in ems) + + New line-height value: + 12px x 1.5 = 18px (old line-height) + 18px x 4 = 72px + 72px / 5 = 14.4px (new line height) + 14.4px / 10px = 1.44 (new line height in em's) */ + +p.incr, .incr p { + font-size: 10px; + line-height: 1.44em; + margin-bottom: 1.5em; +} + + +/* Surround uppercase words and abbreviations with this class. + Based on work by Jørgen Arnor GÃ¥rdsø Lom [http://twistedintellect.com/] */ + +.caps { + font-variant: small-caps; + letter-spacing: 1px; + text-transform: lowercase; + font-size:1.2em; + line-height:1%; + font-weight:bold; + padding:0 2px; +} diff --git a/blueprint/print.css b/blueprint/print.css new file mode 100644 index 0000000..6618614 --- /dev/null +++ b/blueprint/print.css @@ -0,0 +1,29 @@ +/* ----------------------------------------------------------------------- + + Blueprint CSS Framework 0.7.1 + http://blueprintcss.googlecode.com + + * Copyright (c) 2007-2008. See LICENSE for more info. + * See README for instructions on how to use Blueprint. + * For credits and origins, see AUTHORS. + * This is a compressed file. See the sources in the 'src' directory. + +----------------------------------------------------------------------- */ + +/* print.css */ +body {line-height:1.5;font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;color:#000;background:none;font-size:10pt;} +.container {background:none;} +hr {background:#ccc;color:#ccc;width:100%;height:2px;margin:2em 0;padding:0;border:none;} +hr.space {background:#fff;color:#fff;} +h1, h2, h3, h4, h5, h6 {font-family:"Helvetica Neue", Arial, "Lucida Grande", sans-serif;} +code {font:.9em "Courier New", Monaco, Courier, monospace;} +img {float:left;margin:1.5em 1.5em 1.5em 0;} +a img {border:none;} +p img.top {margin-top:0;} +blockquote {margin:1.5em;padding:1em;font-style:italic;font-size:.9em;} +.small {font-size:.9em;} +.large {font-size:1.1em;} +.quiet {color:#999;} +.hide {display:none;} +a:link, a:visited {background:transparent;font-weight:700;text-decoration:underline;} +a:link:after, a:visited:after {content:" (" attr(href) ") ";font-size:90%;} \ No newline at end of file diff --git a/blueprint/screen.css b/blueprint/screen.css new file mode 100644 index 0000000..cedd1f8 --- /dev/null +++ b/blueprint/screen.css @@ -0,0 +1,255 @@ +/* ----------------------------------------------------------------------- + + Blueprint CSS Framework 0.7.1 + http://blueprintcss.googlecode.com + + * Copyright (c) 2007-2008. See LICENSE for more info. + * See README for instructions on how to use Blueprint. + * For credits and origins, see AUTHORS. + * This is a compressed file. See the sources in the 'src' directory. + +----------------------------------------------------------------------- */ + +/* reset.css */ +html, body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, code, del, dfn, em, img, q, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td {margin:0;padding:0;border:0;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit;vertical-align:baseline;} +body {line-height:1.5;} +table {border-collapse:separate;border-spacing:0;} +caption, th, td {text-align:left;font-weight:normal;} +table, td, th {vertical-align:middle;} +blockquote:before, blockquote:after, q:before, q:after {content:"";} +blockquote, q {quotes:"" "";} +a img {border:none;} + +/* additional classes */ +.shadow { +-webkit-box-shadow: 0px 5px 5px #888; +-moz-box-shadow: 0px 5px 5px #888; +} + +/* typography.css */ +body {font-size:75%;color:#222;background:#fff;font-family:"HelveticaNeue", Helvetica, "GillSans", Arial, sans-serif;} +h1, h2, h3, h4, h5, h6 {font-weight:normal;color:#111;} +h1 {margin-bottom:0.5em; + font: 3em/1 GillSans-Light; +} +h2 {font-size:2em;margin-bottom:0.75em;} +h3 {font-size:1.5em;line-height:1;margin-bottom:1em;} +h4 {font-size:1.2em;line-height:1.25;margin-bottom:1.25em;height:1.25em;} +h5 {font-size:1em;font-weight:bold;margin-bottom:1.5em;} +h6 {font-size:1em;font-weight:bold;} +h1 img, h2 img, h3 img, h4 img, h5 img, h6 img {margin:0;} +p {margin:0 0 1.5em;} +p img {float:left;margin:1.5em 1.5em 1.5em 0;padding:0;} +p img.right {float:right;margin:1.5em 0 1.5em 1.5em;} +a:focus, a:hover {color:#000;} +a {color:#009;text-decoration:underline;} +blockquote {margin:1.5em;color:#666;font-style:italic;} +strong {font-weight:bold;} +em, dfn {font-style:italic;} +dfn {font-weight:bold;} +sup, sub {line-height:0;} +abbr, acronym {border-bottom:1px dotted #666;} +address {margin:0 0 1.5em;font-style:italic;} +del {color:#666;} +pre, code {margin:1.5em 0;white-space:pre;} +pre, code, tt {font:1em 'andale mono', 'lucida console', monospace;line-height:1.5;} +li ul, li ol {margin:0 1.5em;} +ul, ol {margin:0 1.5em 1.5em 1.5em;} +ul {list-style-type:disc;} +.nest-2 { + list-style-type: circle; +} +.publist{ + list-style-type: none; + padding: 0; + margin: 0; + margin-bottom: 20px; + padding-bottom: 20px; +} +.pub { + margin-bottom: 20px; +} +ol {list-style-type:decimal;} +dl {margin:0 0 1.5em 0;} +dl dt {font-weight:bold;} +dd {margin-left:1.5em;} +table {margin-bottom:1.4em;width:100%;} +th {font-weight:bold;background:#C3D9FF;} +th, td {padding:4px 10px 4px 5px;} +tr.even td {background:#E5ECF9;} +tfoot {font-style:italic;} +caption {background:#eee;} +.pcaption { + padding: 0.2em; + text-align: center; + text-align: justify; + width: auto; + border-top: none; + color: #666; + } +.small {font-size:.8em;margin-bottom:1.875em;line-height:1.875em;} +.large {font-size:1.2em;line-height:2.5em;margin-bottom:1.25em;} +.hide {display:none;} +.quiet {color:#666;} +.loud {color:#000;} +.highlight {background:#ff0;} +.added {background:#060;color:#fff;} +.removed {background:#900;color:#fff;} +.first {margin-left:0;padding-left:0;} +.last {margin-right:0;padding-right:0;} +.top {margin-top:0;padding-top:0;} +.bottom {margin-bottom:0;padding-bottom:0;} + +/* grid.css */ +.container {width:820px;margin:0 auto;} +.showgrid {background:url(src/grid.png);} +body {margin:1.5em 0;} +div.span-1, div.span-2, div.span-3, div.span-4, div.span-5, div.span-6, div.span-7, div.span-8, div.span-9, div.span-10, div.span-11, div.span-12, div.span-13, div.span-14, div.span-15, div.span-16, div.span-17, div.span-18, div.span-19, div.span-20, div.span-21, div.span-22, div.span-23, div.span-24 {float:left;margin-right:10px;} +div.last {margin-right:0;} +.span-1 {width:30px;} +.span-2 {width:70px;} +.span-3 {width:110px;} +.span-4 {width:150px;} +.span-5 {width:190px;} +.span-6 {width:230px;} +.span-7 {width:270px;} +.span-8 {width:310px;} +.span-9 {width:350px;} +.span-10 {width:390px;} +.span-11 {width:430px;} +.span-12 {width:470px;} +.span-13 {width:510px;} +.span-14 {width:550px;} +.span-15 {width:590px;} +.span-16 {width:630px;} +.span-17 {width:670px;} +.span-18 {width:710px;} +.span-19 {width:750px;} +.span-20 {width:790px;} +.span-21 {width:830px;} +.span-22 {width:870px;} +.span-23 {width:910px;} +.span-24, div.span-24 {width:950px;margin:0;} +.append-1 {padding-right:40px;} +.append-2 {padding-right:80px;} +.append-3 {padding-right:120px;} +.append-4 {padding-right:160px;} +.append-5 {padding-right:200px;} +.append-6 {padding-right:240px;} +.append-7 {padding-right:280px;} +.append-8 {padding-right:320px;} +.append-9 {padding-right:360px;} +.append-10 {padding-right:400px;} +.append-11 {padding-right:440px;} +.append-12 {padding-right:480px;} +.append-13 {padding-right:520px;} +.append-14 {padding-right:560px;} +.append-15 {padding-right:600px;} +.append-16 {padding-right:640px;} +.append-17 {padding-right:680px;} +.append-18 {padding-right:720px;} +.append-19 {padding-right:760px;} +.append-20 {padding-right:800px;} +.append-21 {padding-right:840px;} +.append-22 {padding-right:880px;} +.append-23 {padding-right:920px;} +.prepend-1 {padding-left:40px;} +.prepend-2 {padding-left:80px;} +.prepend-3 {padding-left:120px;} +.prepend-4 {padding-left:160px;} +.prepend-5 {padding-left:200px;} +.prepend-6 {padding-left:240px;} +.prepend-7 {padding-left:280px;} +.prepend-8 {padding-left:320px;} +.prepend-9 {padding-left:360px;} +.prepend-10 {padding-left:400px;} +.prepend-11 {padding-left:440px;} +.prepend-12 {padding-left:480px;} +.prepend-13 {padding-left:520px;} +.prepend-14 {padding-left:560px;} +.prepend-15 {padding-left:600px;} +.prepend-16 {padding-left:640px;} +.prepend-17 {padding-left:680px;} +.prepend-18 {padding-left:720px;} +.prepend-19 {padding-left:760px;} +.prepend-20 {padding-left:800px;} +.prepend-21 {padding-left:840px;} +.prepend-22 {padding-left:880px;} +.prepend-23 {padding-left:920px;} +div.border {padding-right:4px;margin-right:5px;border-right:1px solid #eee;} +div.colborder {padding-right:24px;margin-right:25px;border-right:1px solid #eee;} +.pull-1 {margin-left:-40px;} +.pull-2 {margin-left:-80px;} +.pull-3 {margin-left:-120px;} +.pull-4 {margin-left:-160px;} +.pull-5 {margin-left:-200px;} +.pull-6 {margin-left:-240px;} +.pull-7 {margin-left:-280px;} +.pull-8 {margin-left:-320px;} +.pull-9 {margin-left:-360px;} +.pull-10 {margin-left:-400px;} +.pull-11 {margin-left:-440px;} +.pull-12 {margin-left:-480px;} +.pull-13 {margin-left:-520px;} +.pull-14 {margin-left:-560px;} +.pull-15 {margin-left:-600px;} +.pull-16 {margin-left:-640px;} +.pull-17 {margin-left:-680px;} +.pull-18 {margin-left:-720px;} +.pull-19 {margin-left:-760px;} +.pull-20 {margin-left:-800px;} +.pull-21 {margin-left:-840px;} +.pull-22 {margin-left:-880px;} +.pull-23 {margin-left:-920px;} +.pull-24 {margin-left:-960px;} +.pull-1, .pull-2, .pull-3, .pull-4, .pull-5, .pull-6, .pull-7, .pull-8, .pull-9, .pull-10, .pull-11, .pull-12, .pull-13, .pull-14, .pull-15, .pull-16, .pull-17, .pull-18, .pull-19, .pull-20, .pull-21, .pull-22, .pull-23, .pull-24 {float:left;position:relative;} +.push-1 {margin:0 -40px 1.5em 40px;} +.push-2 {margin:0 -80px 1.5em 80px;} +.push-3 {margin:0 -120px 1.5em 120px;} +.push-4 {margin:0 -160px 1.5em 160px;} +.push-5 {margin:0 -200px 1.5em 200px;} +.push-6 {margin:0 -240px 1.5em 240px;} +.push-7 {margin:0 -280px 1.5em 280px;} +.push-8 {margin:0 -320px 1.5em 320px;} +.push-9 {margin:0 -360px 1.5em 360px;} +.push-10 {margin:0 -400px 1.5em 400px;} +.push-11 {margin:0 -440px 1.5em 440px;} +.push-12 {margin:0 -480px 1.5em 480px;} +.push-13 {margin:0 -520px 1.5em 520px;} +.push-14 {margin:0 -560px 1.5em 560px;} +.push-15 {margin:0 -600px 1.5em 600px;} +.push-16 {margin:0 -640px 1.5em 640px;} +.push-17 {margin:0 -680px 1.5em 680px;} +.push-18 {margin:0 -720px 1.5em 720px;} +.push-19 {margin:0 -760px 1.5em 760px;} +.push-20 {margin:0 -800px 1.5em 800px;} +.push-21 {margin:0 -840px 1.5em 840px;} +.push-22 {margin:0 -880px 1.5em 880px;} +.push-23 {margin:0 -920px 1.5em 920px;} +.push-24 {margin:0 -960px 1.5em 960px;} +.push-1, .push-2, .push-3, .push-4, .push-5, .push-6, .push-7, .push-8, .push-9, .push-10, .push-11, .push-12, .push-13, .push-14, .push-15, .push-16, .push-17, .push-18, .push-19, .push-20, .push-21, .push-22, .push-23, .push-24 {float:right;position:relative;} +.box {padding:1.5em;margin-bottom:1.5em;background:#E5ECF9;} +hr {background:#ddd;color:#ddd;clear:both;float:none;width:100%;height:.1em;margin:0 0 1.45em;border:none;} +hr.space {background:#fff;color:#fff;} +.clearfix:after, .container:after {content:".";display:block;height:0;clear:both;visibility:hidden;} +.clearfix, .container {display:inline-block;} +* html .clearfix, * html .container {height:1%;} +.clearfix, .container {display:block;} +.clear {clear:both;} + +/* forms.css */ +label {font-weight:bold;} +fieldset {padding:1.4em;margin:0 0 1.5em 0;border:1px solid #ccc;} +legend {font-weight:bold;font-size:1.2em;} +input.text, input.title, textarea, select {margin:0.5em 0;border:1px solid #bbb;} +input.text:focus, input.title:focus, textarea:focus, select:focus {border:1px solid #666;} +input.text, input.title {width:300px;padding:5px;} +input.title {font-size:1.5em;} +textarea {width:390px;height:250px;padding:5px;} +.error, .notice, .success {padding:.8em;margin-bottom:1em;border:2px solid #ddd;} +.error {background:#FBE3E4;color:#8a1f11;border-color:#FBC2C4;} +.notice {background:#FFF6BF;color:#514721;border-color:#FFD324;} +.success {background:#E6EFC2;color:#264409;border-color:#C6D880;} +.error a {color:#8a1f11;} +.notice a {color:#514721;} +.success a {color:#264409;} \ No newline at end of file diff --git a/blueprint/src/forms.css b/blueprint/src/forms.css new file mode 100755 index 0000000..c075be7 --- /dev/null +++ b/blueprint/src/forms.css @@ -0,0 +1,49 @@ +/* -------------------------------------------------------------- + + forms.css + * Sets up some default styling for forms + * Gives you classes to enhance your forms + + Usage: + * For text fields, use class .title or .text + +-------------------------------------------------------------- */ + +label { font-weight: bold; } +fieldset { padding:1.4em; margin: 0 0 1.5em 0; border: 1px solid #ccc; } +legend { font-weight: bold; font-size:1.2em; } + + +/* Form fields +-------------------------------------------------------------- */ + +input.text, input.title, +textarea, select { + margin:0.5em 0; + border:1px solid #bbb; +} + +input.text:focus, input.title:focus, +textarea:focus, select:focus { + border:1px solid #666; +} + +input.text, +input.title { width: 300px; padding:5px; } +input.title { font-size:1.5em; } +textarea { width: 390px; height: 250px; padding:5px; } + + +/* Success, notice and error boxes +-------------------------------------------------------------- */ + +.error, +.notice, +.success { padding: .8em; margin-bottom: 1em; border: 2px solid #ddd; } + +.error { background: #FBE3E4; color: #8a1f11; border-color: #FBC2C4; } +.notice { background: #FFF6BF; color: #514721; border-color: #FFD324; } +.success { background: #E6EFC2; color: #264409; border-color: #C6D880; } +.error a { color: #8a1f11; } +.notice a { color: #514721; } +.success a { color: #264409; } diff --git a/blueprint/src/grid.css b/blueprint/src/grid.css new file mode 100755 index 0000000..301f716 --- /dev/null +++ b/blueprint/src/grid.css @@ -0,0 +1,216 @@ +/* -------------------------------------------------------------- + + grid.css + * Sets up an easy-to-use grid of 24 columns. + + By default, the grid is 950px wide, with 24 columns + spanning 30px, and a 10px margin between columns. + + If you need fewer or more columns, namespaces or semantic + element names, use the compressor script (lib/compress.rb) + + Note: Changes made in this file will not be applied when + using the compressor: make changes in lib/blueprint/grid.css.rb + +-------------------------------------------------------------- */ + +/* A container should group all your columns. */ +.container { + width: 950px; + margin: 0 auto; +} + +/* Use this class on any div.span / container to see the grid. */ +.showgrid { + background: url(src/grid.png); +} + +/* Body margin for a sensile default look. */ +body { + margin:1.5em 0; +} + + +/* Columns +-------------------------------------------------------------- */ + +/* Sets up basic grid floating and margin. */ +div.span-1, div.span-2, div.span-3, div.span-4, div.span-5, +div.span-6, div.span-7, div.span-8, div.span-9, div.span-10, +div.span-11, div.span-12, div.span-13, div.span-14, div.span-15, +div.span-16, div.span-17, div.span-18, div.span-19, div.span-20, +div.span-21, div.span-22, div.span-23, div.span-24 { + float: left; + margin-right: 10px; +} + +/* The last column in a row needs this class. */ +div.last { margin-right: 0; } + +/* Use these classes to set the width of a column. */ +.span-1 { width: 30px; } +.span-2 { width: 70px; } +.span-3 { width: 110px; } +.span-4 { width: 150px; } +.span-5 { width: 190px; } +.span-6 { width: 230px; } +.span-7 { width: 270px; } +.span-8 { width: 310px; } +.span-9 { width: 350px; } +.span-10 { width: 390px; } +.span-11 { width: 430px; } +.span-12 { width: 470px; } +.span-13 { width: 510px; } +.span-14 { width: 550px; } +.span-15 { width: 590px; } +.span-16 { width: 630px; } +.span-17 { width: 670px; } +.span-18 { width: 710px; } +.span-19 { width: 750px; } +.span-20 { width: 790px; } +.span-21 { width: 830px; } +.span-22 { width: 870px; } +.span-23 { width: 910px; } +.span-24, div.span-24 { width: 950px; margin: 0; } + +/* Add these to a column to append empty cols. */ +.append-1 { padding-right: 40px; } +.append-2 { padding-right: 80px; } +.append-3 { padding-right: 120px; } +.append-4 { padding-right: 160px; } +.append-5 { padding-right: 200px; } +.append-6 { padding-right: 240px; } +.append-7 { padding-right: 280px; } +.append-8 { padding-right: 320px; } +.append-9 { padding-right: 360px; } +.append-10 { padding-right: 400px; } +.append-11 { padding-right: 440px; } +.append-12 { padding-right: 480px; } +.append-13 { padding-right: 520px; } +.append-14 { padding-right: 560px; } +.append-15 { padding-right: 600px; } +.append-16 { padding-right: 640px; } +.append-17 { padding-right: 680px; } +.append-18 { padding-right: 720px; } +.append-19 { padding-right: 760px; } +.append-20 { padding-right: 800px; } +.append-21 { padding-right: 840px; } +.append-22 { padding-right: 880px; } +.append-23 { padding-right: 920px; } + +/* Add these to a column to prepend empty cols. */ +.prepend-1 { padding-left: 40px; } +.prepend-2 { padding-left: 80px; } +.prepend-3 { padding-left: 120px; } +.prepend-4 { padding-left: 160px; } +.prepend-5 { padding-left: 200px; } +.prepend-6 { padding-left: 240px; } +.prepend-7 { padding-left: 280px; } +.prepend-8 { padding-left: 320px; } +.prepend-9 { padding-left: 360px; } +.prepend-10 { padding-left: 400px; } +.prepend-11 { padding-left: 440px; } +.prepend-12 { padding-left: 480px; } +.prepend-13 { padding-left: 520px; } +.prepend-14 { padding-left: 560px; } +.prepend-15 { padding-left: 600px; } +.prepend-16 { padding-left: 640px; } +.prepend-17 { padding-left: 680px; } +.prepend-18 { padding-left: 720px; } +.prepend-19 { padding-left: 760px; } +.prepend-20 { padding-left: 800px; } +.prepend-21 { padding-left: 840px; } +.prepend-22 { padding-left: 880px; } +.prepend-23 { padding-left: 920px; } + + +/* Border on right hand side of a column. */ +div.border { + padding-right: 4px; + margin-right: 5px; + border-right: 1px solid #eee; +} + +/* Border with more whitespace, spans one column. */ +div.colborder { + padding-right: 24px; + margin-right: 25px; + border-right: 1px solid #eee; +} + + +/* Use these classes on an element to push it into the + next column, or to pull it into the previous column. */ + +.pull-1 { margin-left: -40px; } +.pull-2 { margin-left: -80px; } +.pull-3 { margin-left: -120px; } +.pull-4 { margin-left: -160px; } +.pull-5 { margin-left: -200px; } + +.pull-1, .pull-2, .pull-3, +.pull-4, .pull-5, .pull-5 { + float:left; + position:relative; +} + +.push-1 { margin: 0 -40px 1.5em 40px; } +.push-2 { margin: 0 -80px 1.5em 80px; } +.push-3 { margin: 0 -120px 1.5em 120px; } +.push-4 { margin: 0 -160px 1.5em 160px; } +.push-5 { margin: 0 -200px 1.5em 200px; } + +.push-0, .push-1, .push-2, +.push-3, .push-4, .push-5 { + float: right; + position:relative; +} + + +/* Misc classes and elements +-------------------------------------------------------------- */ + +/* Use a .box to create a padded box inside a column. */ +.box { + padding: 1.5em; + margin-bottom: 1.5em; + background: #E5ECF9; +} + +/* Use this to create a horizontal ruler across a column. */ +hr { + background: #ddd; + color: #ddd; + clear: both; + float: none; + width: 100%; + height: .1em; + margin: 0 0 1.45em; + border: none; +} +hr.space { + background: #fff; + color: #fff; +} + + +/* Clearing floats without extra markup + Based on How To Clear Floats Without Structural Markup by PiE + [http://www.positioniseverything.net/easyclearing.html] */ + +.clearfix:after, .container:after { + content: "."; + display: block; + height: 0; + clear: both; + visibility: hidden; +} +.clearfix, .container {display: inline-block;} +* html .clearfix, +* html .container {height: 1%;} +.clearfix, .container {display: block;} + +/* Regular clearing + apply to column that should drop below previous ones. */ + +.clear { clear:both; } diff --git a/blueprint/src/grid.png b/blueprint/src/grid.png new file mode 100644 index 0000000..129d4a2 Binary files /dev/null and b/blueprint/src/grid.png differ diff --git a/blueprint/src/ie.css b/blueprint/src/ie.css new file mode 100755 index 0000000..fed798d --- /dev/null +++ b/blueprint/src/ie.css @@ -0,0 +1,35 @@ +/* -------------------------------------------------------------- + + ie.css + + Contains every hack for Internet Explorer, + so that our core files stay sweet and nimble. + +-------------------------------------------------------------- */ + +/* Make sure the layout is centered in IE5 */ +body { text-align: center; } +.container { text-align: left; } + +/* Fixes IE margin bugs */ +* html .column { overflow-x: hidden; } + + +/* Elements +-------------------------------------------------------------- */ + +/* Fixes incorrect styling of legend in IE6. */ +* html legend { margin:-18px -8px 16px 0; padding:0; } + +/* Fixes incorrect placement of ol numbers in IE6/7. */ +ol { margin-left:2em; } + +/* Fixes wrong line-height on sup/sub in IE. */ +sup { vertical-align: text-top; } +sub { vertical-align: text-bottom; } + +/* Fixes IE7 missing wrapping of code elements. */ +html>body p code { *white-space: normal; } + +/* IE 6&7 has problems with setting proper <hr> margins. */ +hr { margin: -8px auto 11px; } diff --git a/blueprint/src/print.css b/blueprint/src/print.css new file mode 100755 index 0000000..719e40c --- /dev/null +++ b/blueprint/src/print.css @@ -0,0 +1,85 @@ +/* -------------------------------------------------------------- + + print.css + * Gives you some sensible styles for printing pages. + * See Readme file in this directory for further instructions. + + Some additions you'll want to make, customized to your markup: + #header, #footer, #navigation { display:none; } + +-------------------------------------------------------------- */ + +body { + line-height: 1.5; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + color:#000; + background: none; + font-size: 10pt; +} + + +/* Layout +-------------------------------------------------------------- */ + +.container { + background: none; +} + +hr { + background:#ccc; + color:#ccc; + width:100%; + height:2px; + margin:2em 0; + padding:0; + border:none; +} +hr.space { + background: #fff; + color: #fff; +} + + +/* Text +-------------------------------------------------------------- */ + +h1,h2,h3,h4,h5,h6 { font-family: "Helvetica Neue", Arial, "Lucida Grande", sans-serif; } +code { font:.9em "Courier New", Monaco, Courier, monospace; } + +img { float:left; margin:1.5em 1.5em 1.5em 0; } +a img { border:none; } +p img.top { margin-top: 0; } + +blockquote { + margin:1.5em; + padding:1em; + font-style:italic; + font-size:.9em; +} + +.small { font-size: .9em; } +.large { font-size: 1.1em; } +.quiet { color: #999; } +.hide { display:none; } + + +/* Links +-------------------------------------------------------------- */ + +a:link, a:visited { + background: transparent; + font-weight:700; + text-decoration: underline; +} + +a:link:after, a:visited:after { + content: " (" attr(href) ") "; + font-size: 90%; +} + +/* If you're having trouble printing relative links, uncomment and customize this: + (note: This is valid CSS3, but it still won't go through the W3C CSS Validator) */ + +/* a[href^="/"]:after { + content: " (http://www.yourdomain.com" attr(href) ") "; +} */ diff --git a/blueprint/src/reset.css b/blueprint/src/reset.css new file mode 100755 index 0000000..fc0788c --- /dev/null +++ b/blueprint/src/reset.css @@ -0,0 +1,38 @@ +/* -------------------------------------------------------------- + + reset.css + * Resets default browser CSS. + +-------------------------------------------------------------- */ + +html, body, div, span, object, iframe, +h1, h2, h3, h4, h5, h6, p, blockquote, pre, +a, abbr, acronym, address, code, +del, dfn, em, img, q, dl, dt, dd, ol, ul, li, +fieldset, form, label, legend, +table, caption, tbody, tfoot, thead, tr, th, td { + margin: 0; + padding: 0; + border: 0; + font-weight: inherit; + font-style: inherit; + font-size: 100%; + font-family: inherit; + vertical-align: baseline; +} + +body { + line-height: 1.5; +} + +/* Tables still need 'cellspacing="0"' in the markup. */ +table { border-collapse: separate; border-spacing: 0; } +caption, th, td { text-align: left; font-weight: normal; } +table, td, th { vertical-align: middle; } + +/* Remove possible quote marks (") from <q>, <blockquote>. */ +blockquote:before, blockquote:after, q:before, q:after { content: ""; } +blockquote, q { quotes: "" ""; } + +/* Remove annoying border on linked images. */ +a img { border: none; } diff --git a/blueprint/src/typography.css b/blueprint/src/typography.css new file mode 100755 index 0000000..a686e78 --- /dev/null +++ b/blueprint/src/typography.css @@ -0,0 +1,104 @@ +/* -------------------------------------------------------------- + + typography.css + * Sets up some sensible default typography. + +-------------------------------------------------------------- */ + +/* Default font settings. + The font-size percentage is of 16px. (0.75 * 16px = 12px) */ +body { + font-size: 75%; + color: #222; + background: #fff; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; +} + + +/* Headings +-------------------------------------------------------------- */ + +h1,h2,h3,h4,h5,h6 { font-weight: normal; color: #111; } + +h1 { font-size: 3em; line-height: 1; margin-bottom: 0.5em; } +h2 { font-size: 2em; margin-bottom: 0.75em; } +h3 { font-size: 1.5em; line-height: 1; margin-bottom: 1em; } +h4 { font-size: 1.2em; line-height: 1.25; margin-bottom: 1.25em; height: 1.25em; } +h5 { font-size: 1em; font-weight: bold; margin-bottom: 1.5em; } +h6 { font-size: 1em; font-weight: bold; } + +h1 img, h2 img, h3 img, +h4 img, h5 img, h6 img { + margin: 0; +} + + +/* Text elements +-------------------------------------------------------------- */ + +p { margin: 0 0 1.5em; } +p img { float: left; margin: 1.5em 1.5em 1.5em 0; padding: 0; } +p img.right { float: right; margin: 1.5em 0 1.5em 1.5em; } + +a:focus, +a:hover { color: #000; } +a { color: #009; text-decoration: underline; } + +blockquote { margin: 1.5em; color: #666; font-style: italic; } +strong { font-weight: bold; } +em,dfn { font-style: italic; } +dfn { font-weight: bold; } +sup, sub { line-height: 0; } + +abbr, +acronym { border-bottom: 1px dotted #666; } +address { margin: 0 0 1.5em; font-style: italic; } +del { color:#666; } + +pre,code { margin: 1.5em 0; white-space: pre; } +pre,code,tt { font: 1em 'andale mono', 'lucida console', monospace; line-height: 1.5; } + + +/* Lists +-------------------------------------------------------------- */ + +li ul, +li ol { margin:0 1.5em; } +ul, ol { margin: 0 1.5em 1.5em 1.5em; } + +ul { list-style-type: disc; } +ol { list-style-type: decimal; } + +dl { margin: 0 0 1.5em 0; } +dl dt { font-weight: bold; } +dd { margin-left: 1.5em;} + + +/* Tables +-------------------------------------------------------------- */ + +table { margin-bottom: 1.4em; width:100%; } +th { font-weight: bold; background: #C3D9FF; } +th,td { padding: 4px 10px 4px 5px; } +tr.even td { background: #E5ECF9; } +tfoot { font-style: italic; } +caption { background: #eee; } + + +/* Misc classes +-------------------------------------------------------------- */ + +.small { font-size: .8em; margin-bottom: 1.875em; line-height: 1.875em; } +.large { font-size: 1.2em; line-height: 2.5em; margin-bottom: 1.25em; } +.hide { display: none; } + +.quiet { color: #666; } +.loud { color: #000; } +.highlight { background:#ff0; } +.added { background:#060; color: #fff; } +.removed { background:#900; color: #fff; } + +.first { margin-left:0; padding-left:0; } +.last { margin-right:0; padding-right:0; } +.top { margin-top:0; padding-top:0; } +.bottom { margin-bottom:0; padding-bottom:0; } diff --git a/col.jpg b/col.jpg new file mode 100755 index 0000000..f3f0806 Binary files /dev/null and b/col.jpg differ diff --git a/col.png b/col.png new file mode 100644 index 0000000..aaf6315 Binary files /dev/null and b/col.png differ diff --git a/daniel_j_farrell.jpg b/daniel_j_farrell.jpg new file mode 100644 index 0000000..82f68f4 Binary files /dev/null and b/daniel_j_farrell.jpg differ diff --git a/daniel_j_farrell_square.jpg b/daniel_j_farrell_square.jpg new file mode 100755 index 0000000..00961a6 Binary files /dev/null and b/daniel_j_farrell_square.jpg differ diff --git a/favicon.gif b/favicon.gif new file mode 100644 index 0000000..e69de29 diff --git a/favicon.ico b/favicon.ico new file mode 100644 index 0000000..e69de29 diff --git a/files/fill-bug.dgraph.zip b/files/fill-bug.dgraph.zip new file mode 100644 index 0000000..af24419 Binary files /dev/null and b/files/fill-bug.dgraph.zip differ diff --git a/files/fill-bug.dgraph/.zip b/files/fill-bug.dgraph/.zip new file mode 100644 index 0000000..fe46370 Binary files /dev/null and b/files/fill-bug.dgraph/.zip differ diff --git a/files/fill-bug.dgraph/Columns.plist b/files/fill-bug.dgraph/Columns.plist new file mode 100644 index 0000000..8386f12 Binary files /dev/null and b/files/fill-bug.dgraph/Columns.plist differ diff --git a/files/fill-bug.dgraph/Content.plist b/files/fill-bug.dgraph/Content.plist new file mode 100644 index 0000000..2cd521d Binary files /dev/null and b/files/fill-bug.dgraph/Content.plist differ diff --git a/files/fill-bug.dgraph/Contents/PkgInfo b/files/fill-bug.dgraph/Contents/PkgInfo new file mode 100644 index 0000000..9a9a31b --- /dev/null +++ b/files/fill-bug.dgraph/Contents/PkgInfo @@ -0,0 +1 @@ +DGDcDtPl \ No newline at end of file diff --git a/files/fill-bug.dgraph/QuickLook/Preview.png b/files/fill-bug.dgraph/QuickLook/Preview.png new file mode 100644 index 0000000..d4c5c2a Binary files /dev/null and b/files/fill-bug.dgraph/QuickLook/Preview.png differ diff --git a/files/fill-bug.dgraph/QuickLook/Thumbnail.png b/files/fill-bug.dgraph/QuickLook/Thumbnail.png new file mode 100644 index 0000000..d4c5c2a Binary files /dev/null and b/files/fill-bug.dgraph/QuickLook/Thumbnail.png differ diff --git a/files/fill-bug.dgraph/Spotlight.plist b/files/fill-bug.dgraph/Spotlight.plist new file mode 100644 index 0000000..ed5efdd --- /dev/null +++ b/files/fill-bug.dgraph/Spotlight.plist @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>Labels</key> + <string>y vs x +y vs x +</string> + <key>Text</key> + <string></string> +</dict> +</plist> diff --git a/index copy.html b/index copy.html new file mode 100755 index 0000000..1689f38 --- /dev/null +++ b/index copy.html @@ -0,0 +1,141 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> + +<html lang="en"> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + <meta name="microid" content="mailto+http:sha1:d88ae819ad27750216a14d0338bdd81fb38d2a9a" /> + <link rel="openid.server" href="http://openid.claimid.com/server" /> + <link rel="openid.delegate" href="http://openid.claimid.com/boyfarrell" /> + <title>Daniel J Farrell</title> + + <!-- Framework CSS --> + <link rel="stylesheet" href="blueprint/screen.css" type="text/css" media="screen, projection"> + <link rel="stylesheet" href="blueprint/print.css" type="text/css" media="print"> + <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> + + <!-- Import fancy-type plugin for the sample page. --> + <link rel="stylesheet" href="blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> +</head> + +<body> + + <div class="container"> + <h1 class="light">Daniel J Farrell</h1> + <hr/> + <!-- <h2 class="alt">Research Associate in quantum photovoltaics at Imperial College London</h2> --> + <h2 class="alt">Research student in the Quantum Photovoltaics Group at Imperial College London</h2> + <hr> + + <div class="span-6 colborder"> + <h6>About</h6> + I am in the final stages of completing my PhD under the supervision of Prof. Keith Barnham on the 'Characterisation, modelling and development of Luminescent Solar Concentrators'. I will continue to work on Luminescent Concentrators and Quantum Dots in the group at Imperial College over the coming months. <!--I have completed extensive experimental and computational work on wave-guide structures and am currently investigating optical thin-films. I other areas I have advised a large multinational on commercialisation of a building integrate photovoltaic product. --> + <!--Photovoltaics (PV) is the science of electrical power generation by the direct conversion of solar energy. In our research group we are looking a new material and have pioneered the use of nano-structures to make solar energy cheaper.!--> + </div> + + <div class="span-6 colborder"> + <h6>Research Interests</h6> + <ul> + <li>Photovoltaic cells</li> + <li>Luminescent concentrators</li> + <li>Nano-materials: + <ul class="nest-2"><li>Quantum dots and rod</li> + <li>Organic dyes</li> + </ul> + <li>Building integrated photovoltaics</li> + <li>Thin-film optical coatings + <li>Thermodynamics of dissipative structures</li> + <li>Computer modelling</li> + </ul> + </div> + + <div class="span-5 last"> + <h6>Contact</h6> + <p>Mr. Daniel J Farrell<br> + Experimental Solid State Physics<br> + Blackett Laboratory,<br> + Imperial College London,<br> + Prince Consort Road,<br> + London SW7 2AZ.<br> + U.K. <br> + e-mail: <a href="mailto:[email protected]">[email protected]</a><br> + tel: (+44) - (0)20 7995 6678 + </p> + </div> + <hr> + <hr class="space"> + + <div class="span-13 append-5 colborder"> + <p> + <img src="lsc.jpg" class="top push-0" alt="test"> + <div class="pcaption"> + <p>Luminescent concentrators being illuminated by an uniform light source (conveniently provided by a laptop screen).</p></div> + <h5>Luminescent concentrators</h5> + <p>The luminescent concentrator is a non-tracking approach to the concentration of solar energy. One very important feature of the luminescent concentrator is that it collects diffuse light as well as direct. This is significant, especially for high latitudes where the diffuse can account for 60% of the total insolation. The luminescent concentrator aims to reduced the cost-per-watt of generated power. This is achieved by the geometric and photon concentration factors between the top and edge surfaces.</p> + + <h5>Quantum Dots</h5> + <p>Quantum dots are nanoscale crystals of semiconductor materials. One interesting feature of quantum dots is that their optical properties are size dependent. This is because of <em>quantum confinement</em> of the electron and hole wavefunctions. Our group has proposed replacing organic dyes with quantum dots in luminescent concentrators. This has several advantages; emission colour can be changed by changing the particle size, large red-shifts can be produced by controlling the spread in dot sizes and quantum dots should be inherently more stable than organic materials.</p> + <p>Quantum dots also form the basis of many 3rd generation photovoltaics concepts such as; the intermediate band solar and hot carrier solar cells.</p> + <hr> + <div class="span-13 last"> + <h5>Publications</h5> + <ul class="publist"> + <li class="pub">D J Farrell, A J Chatten, A Büchtemann and K W J Barnham, <strong>“Fabrication, Characterisation and Modelling of Quantum Dot Solar Concentrator Stacks”</strong>, Proc. IEEE 4th World Conference on Photovoltaic Energy Conversion, (Waikoloa, Hawaii, 2006), p217.</li> + + <li class="pub">D J Farrell, A J Chatten, B F Buxton, A Büchtemann, R Danz, M Schleusener, L H Slooff, R Kinderman, A R Burgers, J A M van Roosmalen and K W J Barnham, <strong>“The Luminescent Concentrator: Large Area Modelling And Results With Dye Based Stack Concentrators And Thin-Film Composite Plates”</strong>, Proc. of the 20th European Photovoltaic Solar Energy Conference, (Barcelona, Spain, 2005), p386.</li> + + <li class="pub">D J Farrell, A J Chatten, B F Buxton and K W J Barnham, <strong>"Thermodynamic modelling of the Luminescent Solar Concentrator"</strong>, PVNet-3 UK Conference (Loughborough, UK, 2005).</li> + + </ul> + + <h5>Collaborative publications</h5> + <ul class="publist"> + <li class="pub">R Bose, D J Farrell, A J Chatten, A Büchtemann and K W J Barnham, <strong>“Luminescent Solar Concentrators”</strong>, Proc. Photovoltaic Science Applications and Technology (PVSAT-3), (Durham, UK, 2007), p63.</li> + + <li class="pub">A J Chatten D J Farrell, R Bose, M G Debije, A Büchtemann and K W J Barnham, <strong>“Thermodynamic Modelling of Luminescent Solar Concentrators with Reduced Top Surface Losses”</strong>, abstract accepted: 22nd European Photovoltaic Solar Energy Conference, (Milan, Italy, 2007).</li> + + <li class="pub">A J Chatten, D J Farrell, B F Buxton, A Büchtemann and K W J Barnham, <strong>“Thermodynamic Modelling of Luminescent Solar Concentrators and Modules”</strong>, Proc. of the 21st European Photovoltaic Solar Energy Conference, (Dresden, Germany, 2006), p315.</li> + + <li class="pub">A J Chatten, D J Farrell, B F Buxton, A Büchtemann and K W J Barnham, <strong>“Thermodynamic Modelling of Luminescent Solar Concentrators and Modules”</strong>, Proc. of the 21st European Photovoltaic Solar Energy Conference, (Dresden, Germany, 2006), p315.</li> + + <li class="pub">L H Slooff, R Kinderman, A R Burgers, J A M van Roosmalen, A Büchtemann, A J Chatten, D J Farrell and K W J Barnham, <strong>“The luminescent concentrator: a bright idea for spectrum conversion?”</strong>, Proc. of the 20th European Photovoltaic Solar Energy Conference, (Barcelona, Spain, 2005), p413.</li> + + <li class="pub">A J Chatten, D J Farrell, C Jermyn, P Thomas, B F Buxton, A Büchtemann, R Danz, and K W J Barnham, <strong>“Thermodynamic Modelling of Luminescent Solar Concentrators”</strong>, Proc. 31st IEEE Photovoltaic Specialists Conference, (Orlando, USA, 2005), p82.</li> + + </ul> + <h5>Books & chapters</h5> + <ul class="publist"> + + <li class="pub"><strong>"New Research on Astrophysics, Neutron Stars and Galaxy Clusters edited by Louis V. Ross"</strong>, J. Dunning-Davies and D J Farrell, <strong>"Universal Constants and Black Holes"</strong>, p.67-85, ISBN1-59033-784-0 (2003).</li> + + </ul> + + <h5>Presentations</h5> + <ul class="publist"> + <li class="pub"><strong>“Fabrication, Characterisation and Modelling of Quantum Dot Solar Concentrator Stacks”</strong>, IEEE 4th World Conference on Photovoltaic Energy Conversion, (Waikoloa, Hawaii, 2006).</li> + </ul> + <h5>Poster presentations</h5> + <ul class="publist"> + <li class="pub"><strong>"Thermodynamic modelling of the Luminescent Solar Concentrator"</strong>, PVNet-3 UK Conference (Loughborough, UK, 2005)</li> + <li class="pub"><strong>“The Luminescent Concentrator: Large Area Modelling And Results With Dye Based Stack Concentrators And Thin-Film Composite Plates”</strong>, Proc. of the 20th European Photovoltaic Solar Energy Conference, (Barcelona, Spain, 2005)</li> + </ul> + </div> + </div> + <div class="span-6 last"> + <h3><span class="alt">My links</span></h3> + <p> + <a href="http://www.sc.ic.ac.uk/~q_pv/">Quantum photovoltaics group</a> + <a href="http://www.linkedin.com/in/danieljfarrell">linkedin.com/in/danieljfarrell</a> + <a href="http://identi.ca/danieljfarrell">http://identi.ca/danieljfarrell</a> + </p> + + <h3><span class="alt">My bookmarks</span></h3> + <p><script type="text/javascript" src="http://del.icio.us/feeds/js/boyfarrell?;count=15"></script></p> + + </div> + <hr> + <p class="light">Updated: 22th September 2008</p> + </div> + +</body> +</html> \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..0a92e90 --- /dev/null +++ b/index.html @@ -0,0 +1,134 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> + +<html lang="en"> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London" /> + <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated" /> + <meta name="author" content="Daniel J Farrell" /> + <meta name="microid" content="mailto+http:sha1:ab095e627455a292fb5fd60550b0fa4a2105ae79" /> + <link rel="openid.server" href="http://openid.claimid.com/server" /> + <link rel="openid.delegate" href="http://daniel.farrell.name" /> + <title>Daniel J Farrell</title> + + <!-- Framework CSS --> + <link rel="stylesheet" href="blueprint/screen.css" type="text/css" media="screen, projection"> + <link rel="stylesheet" href="blueprint/print.css" type="text/css" media="print"> + <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> + + <!-- Import fancy-type plugin for the sample page. --> + <link rel="stylesheet" href="blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> +</head> + +<body> + + <div class="container"> + <div class="span-6 colborder"> + <h1 class="light">Daniel J Farrell</h1> + <hr class="space"> + <img src="daniel_j_farrell.jpg" class="top push-0 shadow" alt="test" width="240px"> + </div> + + <h2 class="alt">Research Associate in the <a href="http://www.imperial.ac.uk/qpv">Quantum Photovoltaics Group</a> at Imperial College London</h2> + <p> </p> + <img src="col.png" class="top push-0 shadow" alt="test" width="525px"> + + + <!-- <h2 class="alt">Research Associate in quantum photovoltaics at Imperial College London</h2> --> + + <hr class="space"> + <hr> + + + <div class="span-6 colborder"> + <h6>About</h6> + <p>I am a post doctoral researcher in the Experimental Solid State Physics group at Imperial College London, where I research hot-carrier solar cells, thermodynamics of solar energy conversion and spectral modification with luminescent materials.</p> + + <!--I am in the final stages of completing my PhD under the supervision of Prof. Keith Barnham on the 'Characterisation, modelling and development of Luminescent Solar Concentrators'. I will continue to work on Luminescent Concentrators and Quantum Dots in the group at Imperial College over the coming months.--> <!--I have completed extensive experimental and computational work on wave-guide structures and am currently investigating optical thin-films. I other areas I have advised a large multinational on commercialisation of a building integrate photovoltaic product. --> + <!--Photovoltaics (PV) is the science of electrical power generation by the direct conversion of solar energy. In our research group we are looking a new material and have pioneered the use of nano-structures to make solar energy cheaper.!--> + </div> + + <div class="span-6 colborder"> + <h6>Research Interests</h6> + <ul> + <li>Hot-carrier solar cells</li> + <li>Thermodynamic modelling of solar energy convertors</li> + <li>Luminescent solar concentrators</li> + <li>Nano-materials: + <ul class="nest-2"><li>Quantum dots and rods</li> + <li>Organic dyes</li> + </ul> + <li>Building integrated photovoltaics</li> + <li>Thin-film optical coatings</li> + <li>Monte-Carlo optical modelling</li> + </ul> + </div> + + <div class="span-5 last"> + <h6>Contact</h6> + <p>Dr. Daniel J Farrell<br> + Experimental Solid State Physics<br> + Blackett Laboratory,<br> + Imperial College London,<br> + Prince Consort Road,<br> + London SW7 2AZ.<br> + U.K. <br> + e-mail: <a href="mailto:[email protected]">[email protected]</a><br> + tel: (+44) - (0)20 7594 7305 + </p> + </div> + <hr> + + <div class="span-13 append-5 colborder"> + <p> + <h5>Hot-carrier solar cell</h5> + <!--<p>When sunlight is absorbed by a solar cell, the energy distribution of electrons promoted to the conduction band (and also holes in the valence band) is coherent with the incident spectrum. However, the coherency is rapidly lost (on the scale of femtoseconds) as electron-electron scattering brings the carriers into a thermal distribution with each other. This is known as the hot-carrier phase, because the characteristic temperature is much hotter than the lattice temperature. The electrons are in thermal equilibrium with each other but are not in thermal equilibrium with the lattice. The hot-carrier will steadily cool (in the order of picoseconds) to a thermal distribution characterised by the lattice temperature and a non-zero quasi-fermi level.</p>--> + +<p>Within the framework of the hot-carrier solar cell, thermalisation losses are eliminated by forbidding interactions between charge carriers and the lattice. Energy that would otherwise be lost is stored in the carrier population as heat. Provided that the carriers are thermally isolated from the lattice they may attain a temperature intermediate between that of the Sun and the ambient, and extra energy can be extracted because entropy generation is suppressed.</p> + + <h5>Luminescent concentrators</h5> + + <img src="lsc.jpg" class="top push-0 shadow" alt="test"> + <div class="pcaption"> + <p>Luminescent concentrators being illuminated by an uniform light source (conveniently provided by a laptop screen).</p></div> + + <p>The luminescent concentrator is a non-tracking approach to the concentration of solar energy. One very important feature of the luminescent concentrator is that it collects diffuse light as well as direct. This is significant, especially for high latitudes where the diffuse can account for 60% of the total insolation. The luminescent concentrator aims to reduced the cost-per-watt of generated power. This is achieved by the geometric and photon concentration factors between the top and edge surfaces.</p> + + <h5>Quantum Dots</h5> + <p>Quantum dots are nanoscale crystals of semiconductor materials. One interesting feature of quantum dots is that their optical properties are size dependent. This is because of <em>quantum confinement</em> of the electron and hole wavefunctions. Our group has proposed replacing organic dyes with quantum dots in luminescent concentrators. This has several advantages; emission colour can be changed by changing the particle size, large red-shifts can be produced by controlling the spread in dot sizes and quantum dots should be inherently more stable than organic materials.</p> + <hr> + <div class="span-13 last"> + <h5> Recent publications and talks</h5> + <ul class="publist"> + <li class="pub">D J Farrell and N J Ekins-Daukes, <strong>"Photovoltaic technology: Relay dye boosts efficiency"</strong>, <a href="http://dx.doi.org/10.1038/nphoton.2009.108">Nature Photonics 3, 373 - 374 (2009) </a></li> + <li class="pub">D J Farrell, Wilfried G J H M van Sark, S T Velthuijsen, R E I Schropp, <strong>Using amorphous silicon solar cells to boost the viability of Luminescent Solar Concentrators</strong>, <a href="http://www.icans23.org">23rd International Conference on Amorphous and Nanocrystalline Semiconductors</a>, August 2009 (<a href="publications/farrell-icans23.pdf">Download Pre-print</a>).</li> + + <li class="publist"> + D J Farrell, <strong>"<a href="publications/arup.html">The next generation of Building Integrated Photovoltaics</a>"</strong>, <a href="http://www.arup.com">Arup Associates</a>, London, (2009). + </li> + <li> + <a href="publications/index.html">Full publication list.</a> + </li> + </ul> + </div> + </div> + <div class="span-6 last"> + <h3><span class="alt">Follow me here...</span></h3> + <p> + <a href="http://www.imperial.ac.uk/qpv">Quantum photovoltaics group</a> + <a href="http://www.linkedin.com/in/danieljfarrell">linkedin.com/in/danieljfarrell</a> + <a href="http://identi.ca/danieljfarrell">http://identi.ca/danieljfarrell</a> + <a href="http://twitter.com/danieljfarrell">http://twitter.com/danieljfarrell</a> + </p> + + <h3><span class="alt">My bookmarks</span></h3> + <p><script type="text/javascript" src="http://feeds.delicious.com/v2/js/boyfarrell?title=&icon=m&count=15&sort=date&extended"></script></p> + + </div> + <hr> + <p class="light">Updated: 5th July 2009</p> + </div> + +</body> +</html> diff --git a/keith/._index.html b/keith/._index.html new file mode 100755 index 0000000..ce58499 Binary files /dev/null and b/keith/._index.html differ diff --git a/keith/1.JPG b/keith/1.JPG new file mode 100755 index 0000000..7d8d933 Binary files /dev/null and b/keith/1.JPG differ diff --git a/keith/2.JPG b/keith/2.JPG new file mode 100755 index 0000000..01a551c Binary files /dev/null and b/keith/2.JPG differ diff --git a/keith/3.JPG b/keith/3.JPG new file mode 100755 index 0000000..961429c Binary files /dev/null and b/keith/3.JPG differ diff --git a/keith/4.JPG b/keith/4.JPG new file mode 100755 index 0000000..6d02120 Binary files /dev/null and b/keith/4.JPG differ diff --git a/keith/5.JPG b/keith/5.JPG new file mode 100755 index 0000000..0e9263d Binary files /dev/null and b/keith/5.JPG differ diff --git a/keith/index.html b/keith/index.html new file mode 100755 index 0000000..b1a2ceb --- /dev/null +++ b/keith/index.html @@ -0,0 +1,32 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> + +<html lang="en"> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + <title>http://homepage.mac.com/danieljfarrell/keith/</title> + + <!-- Framework CSS --> + <link rel="stylesheet" href="../blueprint/screen.css" type="text/css" media="screen, projection"> + <link rel="stylesheet" href="../blueprint/print.css" type="text/css" media="print"> + <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> + + <!-- Import fancy-type plugin for the sample page. --> + <link rel="stylesheet" href="blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> +</head> + +<body> + + <div class="container"> + <h1 class="light">Stained class windows</h1> + <hr/> + <ul> + <li><a href="http://homepage.mac.com/danieljfarrell/keith/1.JPG">http://homepage.mac.com/danieljfarrell/keith/1.JPG</a></li> + <li><a href="http://homepage.mac.com/danieljfarrell/keith/2.JPG">http://homepage.mac.com/danieljfarrell/keith/2.JPG</a></li> + <li><a href="http://homepage.mac.com/danieljfarrell/keith/3.JPG">http://homepage.mac.com/danieljfarrell/keith/3.JPG</a></li> + <li><a href="http://homepage.mac.com/danieljfarrell/keith/4.JPG">http://homepage.mac.com/danieljfarrell/keith/4.JPG</a></li> + <li><a href="http://homepage.mac.com/danieljfarrell/keith/5.JPG">http://homepage.mac.com/danieljfarrell/keith/5.JPG</a></li> + </div> + +</body> +</html> \ No newline at end of file diff --git a/lsc.jpg b/lsc.jpg new file mode 100644 index 0000000..be55d39 Binary files /dev/null and b/lsc.jpg differ diff --git a/publications/arup.html b/publications/arup.html new file mode 100644 index 0000000..4f62016 --- /dev/null +++ b/publications/arup.html @@ -0,0 +1,115 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html> +<head> + <meta name="description" content="Dr. Daniel J Farrell Quantum Photovoltaics Group Imperial College London http://sc.ic.ac.uk/~q_pv http://www.imperial.ac.uk/qpv The next generation of building integrated photovoltaics Acknowledgements The rest of the Quantum Photovoltaics Group: Ben Browne, Louise Hirst, Rahul Bose, Jessica Adams, Markus Fuhrer, 
Ravin Ginige, Mauro Pravettoni Ned
Ekins-Daukes Keith Barnham Amanda Chatten Outline What is Photovoltaics? Present building integrated photovoltaics: Silicon modules Thin-film facades The next generation... “Smart windows” Direct system Direct + Diffuse system Light-bars Acronyms: Photovoltaics = PV Building Integrated PV = BIPV A photovoltaic cell (a.k.a solar cell) behaves like a battery But only gives out power when light hits it Particles of light are called photons What is photovoltaics? Why Building Integrated Photovoltaics (BIPV)? Motivation: Local generation of power when demand is high In the UK 7x the solar energy falls on commercial building than is used inside K.Barnham et al. Nature Materials 5, 161 - 164 (2006)
doi:10.1038/nmat1604 We are treating the solar energy as a problem, but it’s a solution! Blinds to blocklight still require air-con. and lighting. What is photovoltaics?- Efficiency The performance of solar cell is its efficiency efficiency = power out / power in For example: A 1m2 solar cell has... 1000 Watts of solar power incident Produces 200 Watts of electrical power Efficiency = 20% Solar power in Electrical power out What is photovoltaics?- Cost High efficiency must be affordable! Another way of saying this is: What is the cost per Watt of the generated electricity? The cost per Watt should be minimised Current fossil fuel technology can generated electrical power at $1/W Where is photovoltaics in this respect? “This is the world's lowest-cost solar panel, which we believe will make us the first solar manufacturer capable of profitably selling solar panels at as little as 99 cents a watt.” -- Nanosolar, 2008 3 generations of photovoltaics 0 100 200 300 400 500 20 40 60 80 100 Efficiency (%) Cost in US$ for a 1m2 solar module US$0.10/W US$0.20/W US$0.50/W US$1.00/W US$3.50/W Adapted from original by M.Green, UNSW. Examples of 1st and 2nd generation BIPV 1st generation BIPV CIS building Manchester Solar installation by Solar Century 391 kWatts capacity 3200 square meter coverage (122 Wm-2) Can this provide all the power needs? 1st generation BIPV Design options: Utilitarian It gets the job done Bolt on design Truly integrate PV? http://www.solarcentury.co.uk 1st generation BIPV http://www.solarcentury.co.uk Vauxhall Cross, London Designed to incorporate the panels Advances in shape and colour PV Crystalox and NaREC Development of coloured anti-reflection Advances is laser cutting 2nd generation BIPV Can be made semi-transparent Beginning to be truly building integrated. 5%-12% efficiency Arnold Glas, Voltarlux Windows 1st and 2nd generation re-cap Photovoltaic material is made into panels 1st generation silicon wafers 2nd thin-film silicon, CdTe, CIGS, dye-sensitised solar cells 0 100 200 300 400 500 20 40 60 80 100 Efficiency (%) Cost in US$ for a 1m2 solar module US$0.10/W US$0.20/W US$0.50/W US$1.00/W US$3.50/W 1st 1. Conventional silicon PV (Wafer based c-Si) 2. Conventional thin-film PV (a-Si, CdTe) 2nd 3rd generation PV is a ‘concentrator technology’ 3rd generation PV uses: high efficiency materials (e.g. GaAs). very small areas of cell, ~1mm2 very large area of lens and mirror. The lens and mirror used concentrate the sun between 100--1000 times. Concentrator PV farm - SolFocus How can we use 3rd generation PV in buildings? Roof installations: Provide electricity and hot water to the building. 15% efficient PV conversion 45% efficient hot water generation John F.H. Smeltink and Andrew W. Blakers The next generation of BIPV Smart Windows - “Solar Skin from Solar Structure” Smart Windows: Keith Barnham, 2006. Smart Windows Smart Windows: Direct light absorbed Diffuse enters room Lower demand on 
air-conditioning Provides heat and electricity Advantages of the Smart Window concept The direct light is total absorbed in the solar cells: Does not cause interior heating Reduces air-conditioning loads AND produces electricity AND produces hot-water Diffuse light illuminates the room No glare Just diffuse blue sky and white light How does the smart window compare to 2nd generation building integrated PV? Diffuse 2nd Generation
 thin-silicon windows 3rd Generation 
smart windows Direct 21% Electricity Interior illumination 35% 5% 5% 12% Electricity 65% Heat dispersion 22% Heating 78% 65% 22% It’s not sunny all the time... In the UK approx. 50% of the yearly solar energy arrives as diffuse light. Smart Window can still generate significant amount of power Can we design and building integrated system to harvest the diffuse component...? Blue sky and clouds. Luminescent solar concentrators Diffuse Direct Solar cells placed on edges Advantages for BIPV: Concentrates direct and diffuse illumination Interesting colours Interesting shapes Depending on colour and size, 5% efficiency. Non-tracking Freedom to design Luminescent materials in BIPV Luminescent materials in BIPV Mauro Pravettoni Can select shape and colour 5% efficiency Useful for decoration Facades Windows.....? Luminescent materials in BIPV Transparent luminescent materials Tinted windows work well for facades and decoration Windows should remain transparent Absorb invisible wavelengths of light: Ultra-violet (UV) and Infrared (IR). Currently only UV absorbing luminescent materials exist. Smart windows with UV booster Diffuse 3rd Generation 
smart windows Direct 21% Electricity Interior illumination 35% Heat dispersion 22% Heating 65% 22% 33% 23% Electricity 2% absolute gain by using the UV with a luminescent solar concentrator Light-bar smart window Alternative smart window design: Light-bar Remove non-transparent components from the window Dramatically reduces cost Price per watt reduces too. Sunlight focused on to bars that pipe the light to edges. 5%-10% efficiency Conclusion: the next generation of BIPV High efficiency 3rd Generation photovoltaics Integrated into Smart Windows Provide power and heat Reduce air-condition and provide illumination Truly building integrated Coloured luminescent materials as facades and decoration Design freedom UV + IR transparent luminescent materials for windows Boost Smart Window power output all year round Light-bar allow totally transparent Smart Window"/> + <title></title> + <script type="text/javascript" language="javascript"> +// <![CDATA[ + var images = new Array (72); + images[0] = "arup.html_files/arup.001-001.png"; + images[1] = "arup.html_files/arup.002-001.png"; + images[2] = "arup.html_files/arup.003-001.png"; + images[3] = "arup.html_files/arup.003-002.png"; + images[4] = "arup.html_files/arup.004-001.png"; + images[5] = "arup.html_files/arup.004-002.png"; + images[6] = "arup.html_files/arup.004-003.png"; + images[7] = "arup.html_files/arup.004-004.png"; + images[8] = "arup.html_files/arup.005-001.png"; + images[9] = "arup.html_files/arup.006-001.png"; + images[10] = "arup.html_files/arup.006-002.png"; + images[11] = "arup.html_files/arup.006-003.png"; + images[12] = "arup.html_files/arup.006-004.png"; + images[13] = "arup.html_files/arup.007-001.png"; + images[14] = "arup.html_files/arup.007-002.png"; + images[15] = "arup.html_files/arup.008-001.png"; + images[16] = "arup.html_files/arup.008-002.png"; + images[17] = "arup.html_files/arup.008-003.png"; + images[18] = "arup.html_files/arup.008-004.png"; + images[19] = "arup.html_files/arup.009-001.png"; + images[20] = "arup.html_files/arup.010-001.png"; + images[21] = "arup.html_files/arup.011-001.png"; + images[22] = "arup.html_files/arup.012-001.png"; + images[23] = "arup.html_files/arup.013-001.png"; + images[24] = "arup.html_files/arup.014-001.png"; + images[25] = "arup.html_files/arup.015-001.png"; + images[26] = "arup.html_files/arup.016-001.png"; + images[27] = "arup.html_files/arup.017-001.png"; + images[28] = "arup.html_files/arup.017-002.png"; + images[29] = "arup.html_files/arup.018-001.png"; + images[30] = "arup.html_files/arup.019-001.png"; + images[31] = "arup.html_files/arup.020-001.png"; + images[32] = "arup.html_files/arup.021-001.png"; + images[33] = "arup.html_files/arup.022-001.png"; + images[34] = "arup.html_files/arup.022-002.png"; + images[35] = "arup.html_files/arup.022-003.png"; + images[36] = "arup.html_files/arup.023-001.png"; + images[37] = "arup.html_files/arup.023-002.png"; + images[38] = "arup.html_files/arup.023-003.png"; + images[39] = "arup.html_files/arup.023-004.png"; + images[40] = "arup.html_files/arup.023-005.png"; + images[41] = "arup.html_files/arup.023-006.png"; + images[42] = "arup.html_files/arup.024-001.png"; + images[43] = "arup.html_files/arup.025-001.png"; + images[44] = "arup.html_files/arup.026-001.png"; + images[45] = "arup.html_files/arup.027-001.png"; + images[46] = "arup.html_files/arup.028-001.png"; + images[47] = "arup.html_files/arup.029-001.png"; + images[48] = "arup.html_files/arup.029-002.png"; + images[49] = "arup.html_files/arup.029-003.png"; + images[50] = "arup.html_files/arup.029-004.png"; + images[51] = "arup.html_files/arup.029-005.png"; + images[52] = "arup.html_files/arup.029-006.png"; + images[53] = "arup.html_files/arup.030-001.png"; + images[54] = "arup.html_files/arup.030-002.png"; + images[55] = "arup.html_files/arup.030-003.png"; + images[56] = "arup.html_files/arup.031-001.png"; + images[57] = "arup.html_files/arup.031-002.png"; + images[58] = "arup.html_files/arup.031-003.png"; + images[59] = "arup.html_files/arup.031-004.png"; + images[60] = "arup.html_files/arup.031-005.png"; + images[61] = "arup.html_files/arup.031-006.png"; + images[62] = "arup.html_files/arup.031-007.png"; + images[63] = "arup.html_files/arup.031-008.png"; + images[64] = "arup.html_files/arup.032-001.png"; + images[65] = "arup.html_files/arup.032-002.png"; + images[66] = "arup.html_files/arup.032-003.png"; + images[67] = "arup.html_files/arup.032-004.png"; + images[68] = "arup.html_files/arup.032-005.png"; + images[69] = "arup.html_files/arup.032-006.png"; + images[70] = "arup.html_files/arup.032-007.png"; + images[71] = "arup.html_files/arup.032-008.png"; + var index = 0; + function WindowLoaded(evt) + { + document.body.onselectstart = function () { return false; }; + } + function Step(i) + { + GoTo(index + i) + } + function GoTo(newIndex) + { + if(newIndex >= 0 && newIndex < images.length) + { + index = newIndex; + document.Slideshow.src = images[index]; + } + } +// ]]> + </script> +</head> +<body bgcolor="black" onload='WindowLoaded(event);'> + <p align="center"> + <br/> + <br/> + <img name="Slideshow" alt="" src="arup.html_files/arup.001-001.png" onclick="Step(1)"/> + <br/> + <br/> + <input type="image" src="arup.html_files/home.png" onclick="GoTo(0)"/> + &nbsp;&nbsp;&nbsp; + <input type="image" src="arup.html_files/prev.png" onclick="Step(-1)"/> + <input type="image" src="arup.html_files/next.png" onclick="Step(1)"/> + </p> +</body> +</html> \ No newline at end of file diff --git a/publications/arup.html_files/arup.001-001.png b/publications/arup.html_files/arup.001-001.png new file mode 100644 index 0000000..6d6e92d Binary files /dev/null and b/publications/arup.html_files/arup.001-001.png differ diff --git a/publications/arup.html_files/home.png b/publications/arup.html_files/home.png new file mode 100644 index 0000000..8914de3 Binary files /dev/null and b/publications/arup.html_files/home.png differ diff --git a/publications/arup.html_files/next.png b/publications/arup.html_files/next.png new file mode 100644 index 0000000..ae8d51a Binary files /dev/null and b/publications/arup.html_files/next.png differ diff --git a/publications/arup.html_files/prev.png b/publications/arup.html_files/prev.png new file mode 100644 index 0000000..0de9aa0 Binary files /dev/null and b/publications/arup.html_files/prev.png differ diff --git a/publications/farrell-icans23.pdf b/publications/farrell-icans23.pdf new file mode 100644 index 0000000..4590c5f Binary files /dev/null and b/publications/farrell-icans23.pdf differ diff --git a/publications/index.html b/publications/index.html new file mode 100644 index 0000000..89ed94c --- /dev/null +++ b/publications/index.html @@ -0,0 +1,92 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> + +<html lang="en"> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + <meta name="description" content="Description of Daniel J Farrell's research at Imperial College London" /> + <meta name="keywords" content="physics photovoltaics solar cells energy luminescent concentrators hot-carriers PV building integrated" /> + <meta name="author" content="Daniel J Farrell" /> + <meta name="microid" content="mailto+http:sha1:d88ae819ad27750216a14d0338bdd81fb38d2a9a" /> + <link rel="openid.server" href="http://openid.claimid.com/server" /> + <link rel="openid.delegate" href="http://openid.claimid.com/boyfarrell" /> + <title>Daniel J Farrell</title> + + <!-- Framework CSS --> + <link rel="stylesheet" href="../blueprint/screen.css" type="text/css" media="screen, projection"> + <link rel="stylesheet" href="../blueprint/print.css" type="text/css" media="print"> + <!--[if IE]><link rel="stylesheet" href="../../blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> + + <!-- Import fancy-type plugin for the sample page. --> + <link rel="stylesheet" href="../blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> +</head> + +<body> + + <div class="container"> + + <!-- <h2 class="alt">Research Associate in quantum photovoltaics at Imperial College London</h2> --> + <hr> + <hr class="space"> + <a href="../index.html">Home</a> + <hr> + + + + <div class="span-13"> + <h5>Selected publications</h5> + <ul class="publist"> + <li class="pub">D J Farrell, W G J H M van Sark, S T Velthuijsen, R E I Schropp, <strong>Using amorphous silicon solar cells to boost the viability of Luminescent Solar Concentrators</strong>, <a href="http://www.icans23.org">23rd International Conference on Amorphous and Nanocrystalline Semiconductors</a>, August 2009 (<a href="farrell-icans23.pdf">Download Pre-print</a>).</li> + + <li class="pub">D J Farrell and N J Ekins-Daukes, <strong>Photovoltaic technology: Relay dye boosts efficiency</strong>, <a href="http://dx.doi.org/10.1038/nphoton.2009.108">Nature Photonics 3, 373 - 374 (2009) </a></li> + <li class="pub">D J Farrell, A J Chatten, A Büchtemann and K W J Barnham, <strong>“Fabrication, Characterisation and Modelling of Quantum Dot Solar Concentrator Stacks”</strong>, Proc. IEEE 4th World Conference on Photovoltaic Energy Conversion, (Waikoloa, Hawaii, 2006), p217.</li> + + <li class="pub">D J Farrell, A J Chatten, B F Buxton, A Büchtemann, R Danz, M Schleusener, L H Slooff, R Kinderman, A R Burgers, J A M van Roosmalen and K W J Barnham, <strong>“The Luminescent Concentrator: Large Area Modelling And Results With Dye Based Stack Concentrators And Thin-Film Composite Plates”</strong>, Proc. of the 20th European Photovoltaic Solar Energy Conference, (Barcelona, Spain, 2005), p386.</li> + + <li class="pub">D J Farrell, A J Chatten, B F Buxton and K W J Barnham, <strong>"Thermodynamic modelling of the Luminescent Solar Concentrator"</strong>, PVNet-3 UK Conference (Loughborough, UK, 2005).</li> + + </ul> + + <h5>Collaborations</h5> + <ul class="publist"> + <li class="pub">R Bose, D J Farrell, A J Chatten, A Büchtemann and K W J Barnham, <strong>“Luminescent Solar Concentrators”</strong>, Proc. Photovoltaic Science Applications and Technology (PVSAT-3), (Durham, UK, 2007), p63.</li> + + <li class="pub">A J Chatten D J Farrell, R Bose, M G Debije, A Büchtemann and K W J Barnham, <strong>“Thermodynamic Modelling of Luminescent Solar Concentrators with Reduced Top Surface Losses”</strong>, abstract accepted: 22nd European Photovoltaic Solar Energy Conference, (Milan, Italy, 2007).</li> + + <li class="pub">A J Chatten, D J Farrell, B F Buxton, A Büchtemann and K W J Barnham, <strong>“Thermodynamic Modelling of Luminescent Solar Concentrators and Modules”</strong>, Proc. of the 21st European Photovoltaic Solar Energy Conference, (Dresden, Germany, 2006), p315.</li> + + <li class="pub">A J Chatten, D J Farrell, B F Buxton, A Büchtemann and K W J Barnham, <strong>“Thermodynamic Modelling of Luminescent Solar Concentrators and Modules”</strong>, Proc. of the 21st European Photovoltaic Solar Energy Conference, (Dresden, Germany, 2006), p315.</li> + + <li class="pub">L H Slooff, R Kinderman, A R Burgers, J A M van Roosmalen, A Büchtemann, A J Chatten, D J Farrell and K W J Barnham, <strong>“The luminescent concentrator: a bright idea for spectrum conversion?”</strong>, Proc. of the 20th European Photovoltaic Solar Energy Conference, (Barcelona, Spain, 2005), p413.</li> + + <li class="pub">A J Chatten, D J Farrell, C Jermyn, P Thomas, B F Buxton, A Büchtemann, R Danz, and K W J Barnham, <strong>“Thermodynamic Modelling of Luminescent Solar Concentrators”</strong>, Proc. 31st IEEE Photovoltaic Specialists Conference, (Orlando, USA, 2005), p82.</li> + + </ul> + <h5>Books & chapters</h5> + <ul class="publist"> + + <li class="pub"><strong>"New Research on Astrophysics, Neutron Stars and Galaxy Clusters edited by Louis V. Ross"</strong>, J. Dunning-Davies and D J Farrell, <strong>"Universal Constants and Black Holes"</strong>, p.67-85, ISBN1-59033-784-0 (2003).</li> + + </ul> + + <h5>Presentations</h5> + <ul class="publist"> + <li class="pub"><strong>“Fabrication, Characterisation and Modelling of Quantum Dot Solar Concentrator Stacks”</strong>, IEEE 4th World Conference on Photovoltaic Energy Conversion, (Waikoloa, Hawaii, 2006).</li> + </ul> + <h5>Poster presentations</h5> + <ul class="publist"> + <li class="pub"><strong>"Thermodynamic modelling of the Luminescent Solar Concentrator"</strong>, PVNet-3 UK Conference (Loughborough, UK, 2005)</li> + <li class="pub"><strong>“The Luminescent Concentrator: Large Area Modelling And Results With Dye Based Stack Concentrators And Thin-Film Composite Plates”</strong>, Proc. of the 20th European Photovoltaic Solar Energy Conference, (Barcelona, Spain, 2005)</li> + </ul> + <h5>Invited talks</h5> + <ul class="publist"> + <li class="pub"><strong>“The next generation of Building Integrated Photovoltaics”</strong>, Arup, London May 2009.</li> + </ul> + </div> + </div> + <hr> + <p class="light">Updated: 5th July 2009</p> + </div> + +</body> +</html> \ No newline at end of file
leonardteo/OBJViewer
c49f558dcc9c1124bde5eae9bb2d1b1522f010ef
Fixed to work on XCode 4
diff --git a/OBJViewer.cpp b/OBJViewer.cpp index e89d002..923bf89 100644 --- a/OBJViewer.cpp +++ b/OBJViewer.cpp @@ -43,636 +43,636 @@ Global Variables int width = WIDTH; int height = HEIGHT; //Mouse position int mouse_x; int mouse_y; int mouse_down_x; //Mouse position when a user clicks int mouse_down_y; //Mouse clicks states bool left_mouse_down = false; bool middle_mouse_down = false; bool right_mouse_down = false; //Model type int model = 0; //Show Wireframe bool show_wireframe = false; bool shaded_mode = true; //Scene Graph Camera CameraNode* sgCamera; //Temporary variables to facilitate Polar camera float azimuth_change = 0; float twist_change = 0; float elevation_change = 0; float cam_distance_change = 0.0; //Panning temporary variables float pan_x_down = 0; //When the pan button is pushed, record this float pan_y_down = 0; float pan_z_down = 0; float pan_x_change = 0; float pan_y_change = 0; //Orthographic zooming temporary variable float ortho_zoom_change = 0; //Scene Graph Node* rootNode; //Calculating fps int frame = 0; int currenttime = 0; int timebase=0; float fps=0.0f; char s[30]; //For testing PolyMeshNode* humveeNode; /** Draw a 24x24 grid **/ static void grid(int scale = 1) { //Turn off lighting for grid glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); //Start drawing lines glBegin(GL_LINES); glColor3f(0.5, 0.5, 0.5); for (int x=-12; x<=12; x++){ if (x != 0){ glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(-12*scale)); glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(12*scale)); } } for (int z=-12; z<=12; z++){ if (z != 0){ glVertex3f((GLfloat)(-12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); glVertex3f((GLfloat)(12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); } } glEnd(); //Make sure the lines at the origin are nice and different /* glBegin(GL_LINES); glColor3f(0.75, 0.75, 0.75); glVertex3f(0, 0, (GLfloat)(-12*scale)); glVertex3f(0, 0, (GLfloat)(12*scale)); glVertex3f((GLfloat)(-12*scale), 0, 0); glVertex3f((GLfloat)(12*scale), 0, 0); glEnd(); */ //Draw axis glBegin(GL_LINES); //x axis should be red and pointing to positive x glColor3f(1.0, 0.0, 0.0); glVertex3f(0.0, 0.0, 0.0); glVertex3f(12*scale, 0.0, 0.0); glEnd(); //Draw cone glPushMatrix(); glTranslatef(12*scale, 0.0, 0.0); glRotatef(90, 0.0, 1.0, 0.0); glutSolidCone(0.2, 0.75, 8, 3); glPopMatrix(); glBegin(GL_LINES); //y axis glColor3f(0.0, 1.0, 0.0); glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 12*scale, 0.0); glEnd(); //Draw cone glPushMatrix(); glTranslatef(0.0, 12*scale, 0.0); glRotatef(-90, 1.0, 0.0, 0.0); glutSolidCone(0.2, 0.75, 8, 3); glPopMatrix(); glBegin(GL_LINES); //z axis glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 0.0, 12*scale); glEnd(); //Draw cone glPushMatrix(); glTranslatef(0.0, 0.0, 12*scale); glutSolidCone(0.2, 0.75, 8, 3); glPopMatrix(); glFlush(); //Turn lighting back on glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); } static void draw_models() { //Draw using scene graph rootNode->render(); } void drawText(char* string) { char* p; for (p=string; *p; p++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *p); } } /** Calculate and display FPS **/ static void profiler() { glDisable(GL_TEXTURE_2D); //Calculate FPS frame++; //Increment number of frames currenttime = glutGet(GLUT_ELAPSED_TIME); //Get current time //Time is current time, timebase is last time since we took a benchmark if ((currenttime - timebase) > 500) { //Do this every x milliseconds float fps = 1000* (float)frame / (float)(currenttime-timebase); sprintf(s,"FPS: %4.2f", fps ); timebase = currenttime; //Set timebase to current time frame = 0; //Reset number of frames } glColor3f(1.0f, 1.0f, 1.0f); glWindowPos2i(5, 5); drawText(s); glEnable(GL_TEXTURE_2D); } /** Display function **/ static void display() { //Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //Call scene graph camera sgCamera->viewTransform(); //Draw grid grid(); //Wireframe switching //If shaded mode, draw the model with shading, else only draw the wireframe if (shaded_mode){ //Setup polygon offset for drawing wire on shaded glPolygonOffset(1.0, 1.0); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glColor3f(1.0, 1.0, 1.0); //Draw the obj model draw_models(); glDisable(GL_POLYGON_OFFSET_FILL); //If show wireframe, render the wireframe on top of shaded object if (show_wireframe){ glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glColor3f(0.0, 0.0, 0.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); } } else { //Wireframe only glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); glDisable(GL_CULL_FACE); glColor3f(1.0, 1.0, 1.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE); } profiler(); glutSwapBuffers(); } /** Sets the projection **/ static void set_projection() { glViewport(0, 0, width, height); sgCamera->setProjection(width, height); } /** Reshape function **/ static void reshape(int new_width, int new_height) { //Set Global Variables width = new_width; height = new_height; set_projection(); //sgCamera->setProjection(width, height); } /** Keyboard Input **/ static void keyboard_func(unsigned char key, int mx, int my) { switch (key) { //Views case 'c': //Reset views //Destroy and reinitialize camera break; case 'w': //Show Wireframe show_wireframe = show_wireframe == false ? true : false; break; case 's': //Shaded Model shaded_mode = shaded_mode == false ? true : false; break; case 'p': //Perspective sgCamera->perspectiveMode = true; set_projection(); break; case 'o': //Ortho sgCamera->perspectiveMode = false; set_projection(); break; //Alternative zoom case '+': //Zoom forward if (sgCamera->perspectiveMode){ sgCamera->fov -= 1.5f; } else { sgCamera->orthoZoom -= 0.1f; } set_projection(); break; case '-': //Zoom back if (sgCamera->perspectiveMode){ sgCamera->fov += 1.5f; } else { sgCamera->orthoZoom += 0.1f; } set_projection(); break; //Exit case 27: exit(0); } glutPostRedisplay(); } /** Function Keys **/ static void functionKeys(int key, int mx, int my) { } /** Mouse Clicks **/ static void mouse_clicks(int button, int state, int mx, int my) { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) { left_mouse_down = true; //Set mouse down state to true mouse_down_x = mx; //Record screen position of mouse when user clicked left button mouse_down_y = my; //cout << "Left mouse button clicked at:" << mx << ", " << my << endl; } else { left_mouse_down = false; //Add changes to camera sgCamera->azimuth += sgCamera->azimuth_offset; sgCamera->elevation += sgCamera->elevation_offset; sgCamera->azimuth_offset = 0.0f; sgCamera->elevation_offset = 0.0f; } break; case GLUT_RIGHT_BUTTON: //Move camera forward and back if (state == GLUT_DOWN) { right_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { right_mouse_down = false; //Reset camera distance offset sgCamera->distance += sgCamera->distance_offset; sgCamera->distance_offset = 0.0f; //Ortho sgCamera->orthoZoom += ortho_zoom_change; ortho_zoom_change = 0; } break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_DOWN) { middle_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { middle_mouse_down = false; sgCamera->panX += sgCamera->panX_offset; sgCamera->panX_offset = 0.0f; sgCamera->panY += sgCamera->panY_offset; sgCamera->panY_offset = 0.0f; } break; } } /** Mouse Movement **/ static void mouse_move(int mx, int my) { //Only bother processing if mouse button is pressed //Left Mouse Button - Orbit if (left_mouse_down){ sgCamera->azimuth_offset = -(float(mouse_down_x) - float(mx)) / float(width) * 90; sgCamera->elevation_offset = -(float(mouse_down_y) - float(my)) / float(height) * 90; } //Right Mouse Button - Dolly if (right_mouse_down){ if (sgCamera->perspectiveMode) { sgCamera->distance_offset = (float(mouse_down_x) - float(mx)) / float(width) * 10; } else { sgCamera->distance_offset = (float(mouse_down_x) - float(mx)) / float(width); sgCamera->setProjection(width, height); } } //Middle Mouse Button - Panning if (middle_mouse_down){ sgCamera->panX_offset = (float(mouse_down_x) - float(mx)) / float(width) * 5; sgCamera->panY_offset = -(float(mouse_down_y) - float(my)) / float(height) * 5; } //Force redisplay if (left_mouse_down || middle_mouse_down || right_mouse_down){ glutPostRedisplay(); } } /** Enable lighting & materials **/ static void lighting() { glShadeModel(GL_SMOOTH); //glShadeModel(GL_FLAT); //Setup Material GLfloat mat_ambient[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_diffuse[] = {(GLfloat)0.9, (GLfloat)0.9, (GLfloat)0.9, (GLfloat)1.0}; GLfloat mat_specular[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_shininess[] = {(GLfloat)50}; glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); //Setup Light(s) GLfloat light_position[] = {30.0, 30.0, 30.0, 0.0}; GLfloat white_light[] = {1.0, 1.0, 1.0, 1.0}; glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light); glLightfv(GL_LIGHT0, GL_SPECULAR, white_light); //Setup Ambient Light //GLfloat lmodel_ambient[] = {(GLfloat)0.2, (GLfloat)0.2, (GLfloat)0.2, (GLfloat)1.0}; //Turn on lighting glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); } /** Clear out the screen **/ static void init() { //Backface culling glEnable(GL_CULL_FACE); glEnable(GL_TEXTURE_2D); glClearColor(0.0, 0.0, 0.0, 0.0); //Load models - OBJModel* uhtiger = new OBJModel("models/uhtiger.obj"); + OBJModel* uhtiger = new OBJModel("/Users/leonardteo/Documents/UniProjects/OBJViewer/models/uhtiger.obj"); PolyMeshNode* uhTigerNode = new PolyMeshNode(); uhTigerNode->attachModel(uhtiger); - Texture* uhTigerTexture = new Texture("textures/uhtiger.bmp"); + Texture* uhTigerTexture = new Texture("/Users/leonardteo/Documents/UniProjects/OBJViewer/textures/uhtiger.bmp"); uhTigerNode->attachTexture(uhTigerTexture); uhTigerNode->translate->z = 5.0f; - OBJModel* m1abrams = new OBJModel("models/m1abrams.obj"); + OBJModel* m1abrams = new OBJModel("/Users/leonardteo/Documents/UniProjects/OBJViewer/models/m1abrams.obj"); PolyMeshNode* m1AbramsNode = new PolyMeshNode(); m1AbramsNode->attachModel(m1abrams); - Texture* m1AbramsTexture = new Texture("textures/M1_ABRAM.bmp"); + Texture* m1AbramsTexture = new Texture("/Users/leonardteo/Documents/UniProjects/OBJViewer/textures/M1_ABRAM.bmp"); m1AbramsNode->attachTexture(m1AbramsTexture); m1AbramsNode->translate->z = -5.0f; m1AbramsNode->translate->x = -15.0f; - OBJModel* humveehardtop = new OBJModel("models/humveehardtop.obj"); + OBJModel* humveehardtop = new OBJModel("/Users/leonardteo/Documents/UniProjects/OBJViewer/models/humveehardtop.obj"); humveeNode = new PolyMeshNode(); humveeNode->attachModel(humveehardtop); - Texture* humveeTexture = new Texture("textures/humveehardtop.bmp"); + Texture* humveeTexture = new Texture("/Users/leonardteo/Documents/UniProjects/OBJViewer/textures/humveehardtop.bmp"); humveeNode->attachTexture(humveeTexture); humveeNode->rotate->y = -90; //Scene Graph rootNode = new Node(); //121 tanks for (int x=-10; x<10; x++) { for (int z=-10; z<10; z++) { TransformNode* transform = new TransformNode(TRANSLATE); transform->translate->x = x*20; transform->translate->z = z*20; transform->addChild(m1AbramsNode); rootNode->addChild(transform); } } sgCamera = new CameraNode(POLAR); sgCamera->distance = 30.0f; sgCamera->azimuth = 0.0f; sgCamera->elevation = 40.0f; //Set up lighting lighting(); //Anti-Aliasing glEnable (GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glLineWidth (1); } /** Main function **/ int main(int argc, char** argv) { //Get current directory cout << "Firing up OBJViewer" << endl; cout << "===================" << endl << endl; cout << "Camera Motion " << endl; cout << "Orbit: Left click and drag mouse" << endl; cout << "Panning: Middle click and drag mouse" << endl; cout << "Dolly: Right click and drag mouse" << endl << endl; cout << "Viewport Controls " << endl; cout << "w: Toggle wireframe" << endl; cout << "s: Toggle shaded mode" << endl; cout << "p: Perspective mode" << endl; cout << "o: Orthographic mode" << endl; cout << "+ or z: Zoom in" << endl; cout << "- or Z(shift-z): Zoom out" << endl; cout << "c: Reset view" << endl << endl; cout << "Escape: Quit" << endl; glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 100); glutCreateWindow("OBJViewer Test - Leonard Teo"); //Initialize GLEW GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); exit(1); } fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard_func); glutSpecialFunc(functionKeys); glutMouseFunc(mouse_clicks); glutMotionFunc(mouse_move); glutIdleFunc(display); //Set idle function to force refresh glutMainLoop(); exit(0); } \ No newline at end of file
leonardteo/OBJViewer
e957a0209fc0b80a8de8076e2dd83fa2080b2df9
Works on OS X now
diff --git a/CameraNode.h b/CameraNode.h index a5abd9e..d68c880 100644 --- a/CameraNode.h +++ b/CameraNode.h @@ -1,85 +1,85 @@ /* * Camera.h * OBJViewer * * Created by Leonard Teo on 10-10-06. * Copyright 2010 Leonard Teo. All rights reserved. * */ #ifndef CAMERANODE_H #define CAMERANODE_H #include "Node.h" -#include <GL/glew.h> - #ifdef __APPLE__ + #include <GLEW/GLEW.h> #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/GLUT.h> #else + #include <GL/glew.h> #include <GL/glut.h> #endif enum CameraProjection { PERSPECTIVE, ORTHO }; enum CameraType { POLAR, FIRSTPERSON }; /** * Camera class extends Node */ class CameraNode : public Node { public: //Data Members CameraProjection cameraProjection; CameraType cameraType; //Constructor/Destructor CameraNode(CameraType); ~CameraNode(); //@todo: Should these be private? //Members //Third person camera / polar camera float twist; //Roll float elevation; //Pitch float azimuth; //Heading float distance; //Distance from point of interest (assume local origin) float panX; //Used for panning the camera float panY; //Orthographic camera float orthoZoom; //The orthographic zoom factor bool perspectiveMode; //Switch between perspective and ortho //Third person offsets - used for controlling mouse movements where you don't want to write directly to the twist, elevation, azimuth float twist_offset; float elevation_offset; float azimuth_offset; float distance_offset; float panX_offset; float panY_offset; float orthoZoom_offset; //Used for handling mouse in and out //Projection settings float fov; //Field of View float nearPlane; //Near clipping plane float farPlane; //Far clipping plane //Methods void setProjection(int width, int height); void viewTransform(); }; #endif diff --git a/Material.h b/Material.h index 281ee26..4f4a1fd 100644 --- a/Material.h +++ b/Material.h @@ -1,32 +1,30 @@ #ifndef MATERIAL_H #define MATERIAL_H -#include <GL/glew.h> - #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/GLUT.h> #else #include <GL/glut.h> #endif class Material { public: Material(void); ~Material(void); GLfloat ambient[4]; GLfloat diffuse[4]; GLfloat specular[4]; GLfloat shininess[1]; void setAmbient(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha = 1.0f); void setDiffuse(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha = 1.0f); void setSpecular(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha = 1.0f); void setDiffuseAndAmbient(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha = 1.0f); void setShininess(GLfloat power); }; #endif \ No newline at end of file diff --git a/Node.h b/Node.h index e662127..d81eac0 100644 --- a/Node.h +++ b/Node.h @@ -1,63 +1,63 @@ /* * Node.h * OBJViewer * * Created by Leonard Teo on 10-10-05. * */ #ifndef NODE_H #define NODE_H #include <vector> #include <string> -#include <GL/glew.h> - #ifdef __APPLE__ + #include <GLEW/GLEW.h> #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/GLUT.h> #else + #include <GL/glew.h> #include <GL/glut.h> #endif #include "Vector3.h" using namespace std; enum NodeType { POLYMESH, CAMERA, LIGHT, TRANSFORM }; enum RenderType { OPAQUE_OBJECTS, TRANSPARENT_OBJECTS, ALL_OBJECTS }; class Node { public: //Data Members NodeType type; //The type of node this is vector<Node*>* children; //Child nodes Node* parent; //The node's parent string id; //The node's ID so that we can search for a node //Local Transforms Vector3* scale; //Local scaling Vector3* rotate; //Local rotation on x, y, z axes Vector3* translate; //Local translation //Methods Node(); ~Node(); void addChild(Node*); void setParent(Node*); void setTranslation(float x, float y, float z); virtual void render(RenderType renderType = ALL_OBJECTS); virtual void viewTransform(); }; #endif diff --git a/OBJModel.h b/OBJModel.h index 8afbbf9..ae50629 100644 --- a/OBJModel.h +++ b/OBJModel.h @@ -1,102 +1,102 @@ /** My attempt at an OBJ parser Leonard Teo Done: Only supports triangles - remember to triangulate all models To DO: - Generate normals if a model doesn't have them - Handle groups and materials **/ #ifndef OBJMODEL_H #define OBJMODEL_H #include <iostream> #include <fstream> #include <stdio.h> #include <string> #include <vector> //OpenGL libraries -#include <GL/glew.h> - #ifdef __APPLE__ + #include <GLEW/GLEW.h> #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/GLUT.h> #else + #include <GL/glew.h> #include <GL/glut.h> #endif //Teapot Engine Libraries #include "Vector3.h" using namespace std; struct UV { float u; float v; }; class OBJModel { friend class PolyMeshNode; //Make sure that PolyMeshNode can access all data in this class public: //Constructor OBJModel(const char* fileName); //Destructor ~OBJModel(void); //Generate normals - TO DO void generateNormals(); private: //Private data members //Total number of vertices int numVertices; int numFaces; int numUVs; int numNormals; //Data Vector3** vertices; Vector3** normals; UV** uvs; int** index; //2 dimensional arrays: Note these are pointers so that we can do this: this->normals_index[i][j] int** normalsIndex; int** uvIndex; GLfloat* vertexArray; GLfloat* normalsArray; GLfloat* uvArray; GLuint* indexArray; //Straight line array //Vertex buffer object IDs GLuint vbo_vertices; GLuint vbo_normals; GLuint vbo_uvs; GLuint vbo_index; //Initialize the arrays and variables void init(); //Load a model file void load(const char* fileName); //Prepare arrays void prepArrays(); void debugArrays(); }; #endif \ No newline at end of file diff --git a/OBJViewer.cpp b/OBJViewer.cpp index 2cb93ec..e89d002 100644 --- a/OBJViewer.cpp +++ b/OBJViewer.cpp @@ -1,681 +1,678 @@ /** OBJ Viewer **/ //STD libraries #include <iostream> #include <string> //OpenGL libraries -#include <GL/glew.h> - #ifdef __APPLE__ + #include <GLEW/GLEW.h> #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/GLUT.h> #else + #include <GL/glew.h> #include <GL/glut.h> #endif //Engine libraries #include "OBJModel.h" #include "MyBitmap.h" #include "Node.h" #include "TransformNode.h" #include "PolyMeshNode.h" #include "Texture.h" #include "Vector3.h" #include "CameraNode.h" #include "PolarCamera.h" using namespace std; //Default Screen Size const int WIDTH = 640; const int HEIGHT = 480; /** Global Variables **/ //Temporary screen width and height int width = WIDTH; int height = HEIGHT; //Mouse position int mouse_x; int mouse_y; int mouse_down_x; //Mouse position when a user clicks int mouse_down_y; //Mouse clicks states bool left_mouse_down = false; bool middle_mouse_down = false; bool right_mouse_down = false; //Model type int model = 0; //Show Wireframe bool show_wireframe = false; bool shaded_mode = true; //Scene Graph Camera CameraNode* sgCamera; //Temporary variables to facilitate Polar camera float azimuth_change = 0; float twist_change = 0; float elevation_change = 0; float cam_distance_change = 0.0; //Panning temporary variables float pan_x_down = 0; //When the pan button is pushed, record this float pan_y_down = 0; float pan_z_down = 0; float pan_x_change = 0; float pan_y_change = 0; //Orthographic zooming temporary variable float ortho_zoom_change = 0; -//Texture -MyBitmap* texture; -static GLuint texName; - //Scene Graph Node* rootNode; //Calculating fps -int frame = 0, time, timebase=0; +int frame = 0; +int currenttime = 0; +int timebase=0; float fps=0.0f; -int font=(int)GLUT_BITMAP_8_BY_13; char s[30]; //For testing PolyMeshNode* humveeNode; /** Draw a 24x24 grid **/ static void grid(int scale = 1) { //Turn off lighting for grid glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); //Start drawing lines glBegin(GL_LINES); glColor3f(0.5, 0.5, 0.5); for (int x=-12; x<=12; x++){ if (x != 0){ glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(-12*scale)); glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(12*scale)); } } for (int z=-12; z<=12; z++){ if (z != 0){ glVertex3f((GLfloat)(-12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); glVertex3f((GLfloat)(12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); } } glEnd(); //Make sure the lines at the origin are nice and different /* glBegin(GL_LINES); glColor3f(0.75, 0.75, 0.75); glVertex3f(0, 0, (GLfloat)(-12*scale)); glVertex3f(0, 0, (GLfloat)(12*scale)); glVertex3f((GLfloat)(-12*scale), 0, 0); glVertex3f((GLfloat)(12*scale), 0, 0); glEnd(); */ //Draw axis glBegin(GL_LINES); //x axis should be red and pointing to positive x glColor3f(1.0, 0.0, 0.0); glVertex3f(0.0, 0.0, 0.0); glVertex3f(12*scale, 0.0, 0.0); glEnd(); //Draw cone glPushMatrix(); glTranslatef(12*scale, 0.0, 0.0); glRotatef(90, 0.0, 1.0, 0.0); glutSolidCone(0.2, 0.75, 8, 3); glPopMatrix(); glBegin(GL_LINES); //y axis glColor3f(0.0, 1.0, 0.0); glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 12*scale, 0.0); glEnd(); //Draw cone glPushMatrix(); glTranslatef(0.0, 12*scale, 0.0); glRotatef(-90, 1.0, 0.0, 0.0); glutSolidCone(0.2, 0.75, 8, 3); glPopMatrix(); glBegin(GL_LINES); //z axis glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 0.0, 12*scale); glEnd(); //Draw cone glPushMatrix(); glTranslatef(0.0, 0.0, 12*scale); glutSolidCone(0.2, 0.75, 8, 3); glPopMatrix(); glFlush(); //Turn lighting back on glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); } static void draw_models() { //Draw using scene graph rootNode->render(); } void drawText(char* string) { char* p; for (p=string; *p; p++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *p); } } /** Calculate and display FPS **/ static void profiler() { glDisable(GL_TEXTURE_2D); //Calculate FPS frame++; //Increment number of frames - time = glutGet(GLUT_ELAPSED_TIME); //Get current time + currenttime = glutGet(GLUT_ELAPSED_TIME); //Get current time //Time is current time, timebase is last time since we took a benchmark - if ((time - timebase) > 500) { //Do this every x milliseconds + if ((currenttime - timebase) > 500) { //Do this every x milliseconds - float fps = 1000* (float)frame / (float)(time-timebase); + float fps = 1000* (float)frame / (float)(currenttime-timebase); sprintf(s,"FPS: %4.2f", fps ); - timebase = time; //Set timebase to current time + timebase = currenttime; //Set timebase to current time frame = 0; //Reset number of frames } glColor3f(1.0f, 1.0f, 1.0f); glWindowPos2i(5, 5); drawText(s); glEnable(GL_TEXTURE_2D); } /** Display function **/ static void display() { //Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //Call scene graph camera sgCamera->viewTransform(); //Draw grid grid(); //Wireframe switching //If shaded mode, draw the model with shading, else only draw the wireframe if (shaded_mode){ //Setup polygon offset for drawing wire on shaded glPolygonOffset(1.0, 1.0); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glColor3f(1.0, 1.0, 1.0); //Draw the obj model draw_models(); glDisable(GL_POLYGON_OFFSET_FILL); //If show wireframe, render the wireframe on top of shaded object if (show_wireframe){ glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glColor3f(0.0, 0.0, 0.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); } } else { //Wireframe only glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); glDisable(GL_CULL_FACE); glColor3f(1.0, 1.0, 1.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE); } profiler(); glutSwapBuffers(); } /** Sets the projection **/ static void set_projection() { glViewport(0, 0, width, height); sgCamera->setProjection(width, height); } /** Reshape function **/ static void reshape(int new_width, int new_height) { //Set Global Variables width = new_width; height = new_height; set_projection(); //sgCamera->setProjection(width, height); } /** Keyboard Input **/ static void keyboard_func(unsigned char key, int mx, int my) { switch (key) { //Views case 'c': //Reset views //Destroy and reinitialize camera break; case 'w': //Show Wireframe show_wireframe = show_wireframe == false ? true : false; break; case 's': //Shaded Model shaded_mode = shaded_mode == false ? true : false; break; case 'p': //Perspective sgCamera->perspectiveMode = true; set_projection(); break; case 'o': //Ortho sgCamera->perspectiveMode = false; set_projection(); break; //Alternative zoom case '+': //Zoom forward if (sgCamera->perspectiveMode){ sgCamera->fov -= 1.5f; } else { sgCamera->orthoZoom -= 0.1f; } set_projection(); break; case '-': //Zoom back if (sgCamera->perspectiveMode){ sgCamera->fov += 1.5f; } else { sgCamera->orthoZoom += 0.1f; } set_projection(); break; //Exit case 27: exit(0); } glutPostRedisplay(); } /** Function Keys **/ static void functionKeys(int key, int mx, int my) { } /** Mouse Clicks **/ static void mouse_clicks(int button, int state, int mx, int my) { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) { left_mouse_down = true; //Set mouse down state to true mouse_down_x = mx; //Record screen position of mouse when user clicked left button mouse_down_y = my; //cout << "Left mouse button clicked at:" << mx << ", " << my << endl; } else { left_mouse_down = false; //Add changes to camera sgCamera->azimuth += sgCamera->azimuth_offset; sgCamera->elevation += sgCamera->elevation_offset; sgCamera->azimuth_offset = 0.0f; sgCamera->elevation_offset = 0.0f; } break; case GLUT_RIGHT_BUTTON: //Move camera forward and back if (state == GLUT_DOWN) { right_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { right_mouse_down = false; //Reset camera distance offset sgCamera->distance += sgCamera->distance_offset; sgCamera->distance_offset = 0.0f; //Ortho sgCamera->orthoZoom += ortho_zoom_change; ortho_zoom_change = 0; } break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_DOWN) { middle_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { middle_mouse_down = false; sgCamera->panX += sgCamera->panX_offset; sgCamera->panX_offset = 0.0f; sgCamera->panY += sgCamera->panY_offset; sgCamera->panY_offset = 0.0f; } break; } } /** Mouse Movement **/ static void mouse_move(int mx, int my) { //Only bother processing if mouse button is pressed //Left Mouse Button - Orbit if (left_mouse_down){ sgCamera->azimuth_offset = -(float(mouse_down_x) - float(mx)) / float(width) * 90; sgCamera->elevation_offset = -(float(mouse_down_y) - float(my)) / float(height) * 90; } //Right Mouse Button - Dolly if (right_mouse_down){ if (sgCamera->perspectiveMode) { sgCamera->distance_offset = (float(mouse_down_x) - float(mx)) / float(width) * 10; } else { sgCamera->distance_offset = (float(mouse_down_x) - float(mx)) / float(width); sgCamera->setProjection(width, height); } } //Middle Mouse Button - Panning if (middle_mouse_down){ sgCamera->panX_offset = (float(mouse_down_x) - float(mx)) / float(width) * 5; sgCamera->panY_offset = -(float(mouse_down_y) - float(my)) / float(height) * 5; } //Force redisplay if (left_mouse_down || middle_mouse_down || right_mouse_down){ glutPostRedisplay(); } } /** Enable lighting & materials **/ static void lighting() { glShadeModel(GL_SMOOTH); //glShadeModel(GL_FLAT); //Setup Material GLfloat mat_ambient[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_diffuse[] = {(GLfloat)0.9, (GLfloat)0.9, (GLfloat)0.9, (GLfloat)1.0}; GLfloat mat_specular[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_shininess[] = {(GLfloat)50}; glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); //Setup Light(s) GLfloat light_position[] = {30.0, 30.0, 30.0, 0.0}; GLfloat white_light[] = {1.0, 1.0, 1.0, 1.0}; glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light); glLightfv(GL_LIGHT0, GL_SPECULAR, white_light); //Setup Ambient Light //GLfloat lmodel_ambient[] = {(GLfloat)0.2, (GLfloat)0.2, (GLfloat)0.2, (GLfloat)1.0}; //Turn on lighting glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); } /** Clear out the screen **/ static void init() { //Backface culling glEnable(GL_CULL_FACE); glEnable(GL_TEXTURE_2D); glClearColor(0.0, 0.0, 0.0, 0.0); //Load models OBJModel* uhtiger = new OBJModel("models/uhtiger.obj"); PolyMeshNode* uhTigerNode = new PolyMeshNode(); uhTigerNode->attachModel(uhtiger); Texture* uhTigerTexture = new Texture("textures/uhtiger.bmp"); uhTigerNode->attachTexture(uhTigerTexture); uhTigerNode->translate->z = 5.0f; OBJModel* m1abrams = new OBJModel("models/m1abrams.obj"); PolyMeshNode* m1AbramsNode = new PolyMeshNode(); m1AbramsNode->attachModel(m1abrams); Texture* m1AbramsTexture = new Texture("textures/M1_ABRAM.bmp"); m1AbramsNode->attachTexture(m1AbramsTexture); m1AbramsNode->translate->z = -5.0f; m1AbramsNode->translate->x = -15.0f; OBJModel* humveehardtop = new OBJModel("models/humveehardtop.obj"); humveeNode = new PolyMeshNode(); humveeNode->attachModel(humveehardtop); Texture* humveeTexture = new Texture("textures/humveehardtop.bmp"); humveeNode->attachTexture(humveeTexture); humveeNode->rotate->y = -90; //Scene Graph rootNode = new Node(); //121 tanks for (int x=-10; x<10; x++) { for (int z=-10; z<10; z++) { TransformNode* transform = new TransformNode(TRANSLATE); transform->translate->x = x*20; transform->translate->z = z*20; transform->addChild(m1AbramsNode); rootNode->addChild(transform); } } sgCamera = new CameraNode(POLAR); sgCamera->distance = 30.0f; sgCamera->azimuth = 0.0f; sgCamera->elevation = 40.0f; //Set up lighting lighting(); //Anti-Aliasing glEnable (GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glLineWidth (1); } /** Main function **/ int main(int argc, char** argv) { //Get current directory cout << "Firing up OBJViewer" << endl; cout << "===================" << endl << endl; cout << "Camera Motion " << endl; cout << "Orbit: Left click and drag mouse" << endl; cout << "Panning: Middle click and drag mouse" << endl; cout << "Dolly: Right click and drag mouse" << endl << endl; cout << "Viewport Controls " << endl; cout << "w: Toggle wireframe" << endl; cout << "s: Toggle shaded mode" << endl; cout << "p: Perspective mode" << endl; cout << "o: Orthographic mode" << endl; cout << "+ or z: Zoom in" << endl; cout << "- or Z(shift-z): Zoom out" << endl; cout << "c: Reset view" << endl << endl; cout << "Escape: Quit" << endl; glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 100); glutCreateWindow("OBJViewer Test - Leonard Teo"); //Initialize GLEW GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); exit(1); } fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard_func); glutSpecialFunc(functionKeys); glutMouseFunc(mouse_clicks); glutMotionFunc(mouse_move); glutIdleFunc(display); //Set idle function to force refresh glutMainLoop(); exit(0); } \ No newline at end of file diff --git a/PolyMeshNode.h b/PolyMeshNode.h index e332a02..c30eb9e 100644 --- a/PolyMeshNode.h +++ b/PolyMeshNode.h @@ -1,58 +1,58 @@ /* * PolyMesh.h * OBJViewer * * Created by Leonard Teo on 10-10-05. * */ #ifndef POLYMESHNODE_H #define POLYMESHNODE_H #include "Node.h" #include "OBJModel.h" #include "Texture.h" #include "Material.h" -#include <GL\glew.h> - #ifdef __APPLE__ + #include <GLEW/GLEW.h> #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/GLUT.h> #else + #include <GL/glew.h> #include <GL/glut.h> #endif #define BUFFER_OFFSET(bytes) ((GLubyte*) NULL + (bytes)) class PolyMeshNode : public Node { public: //Constructor/Destructor PolyMeshNode(); ~PolyMeshNode(); //Attach model - note that this class does NOT load OBJModels. It attaches them so that you can have instances of models void attachModel(OBJModel* model); //Attach texture void attachTexture(Texture* texture); void attachMaterial(Material* material); //Draw the polygons using OpenGL calls void draw(); //Scene graph rendering call void render(RenderType renderType = ALL_OBJECTS); //Data members OBJModel* mesh; Texture* texture; Material* material; }; #endif
leonardteo/OBJViewer
1aff1bccf85867f3060ed4f003be8698439db984
Latest
diff --git a/CameraNode.cpp b/CameraNode.cpp index e4a63f2..44fdeca 100644 --- a/CameraNode.cpp +++ b/CameraNode.cpp @@ -1,122 +1,124 @@ /* * Camera.cpp * OBJViewer * * Created by Leonard Teo on 10-10-06. * Copyright 2010 Leonard Teo. All rights reserved. * */ #include "CameraNode.h" CameraNode::CameraNode(CameraType cameraType) : Node() { //Set node type this->type = CAMERA; this->cameraType = cameraType; //Polar camera settings this->azimuth = 0.0; this->elevation = 0.0; this->twist = 0.0; this->distance = 0.0; this->panX = 0.0; this->panY = 0.0; this->azimuth_offset = 0.0; this->elevation_offset = 0.0; this->twist_offset = 0.0; this->distance_offset = 0.0; this->panX_offset = 0.0; this->panY_offset = 0.0; + this->orthoZoom_offset = 0.0f; //Default Projection settings this->nearPlane = 0.1f; this->farPlane = 500.0f; this->fov = 45; this->perspectiveMode = true; - this->orthoZoom = 2; + this->orthoZoom = 10; } CameraNode::~CameraNode() { delete this; } /** Sets up a projection for the camera Must provide viewport width and height **/ void CameraNode::setProjection(int width, int height) { - glViewport(0, 0, (GLsizei) width, (GLsizei) height); + glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Perspective mode or ortho float aspect_ratio = (float)width / (float)height; if (this->perspectiveMode){ //If perspective mode, set up a perspective projection gluPerspective(this->fov, GLfloat(aspect_ratio), this->nearPlane, this->farPlane); } else { //If orthographic mode, set up an orthographic projection //Keep aspect ratio float left, right, bottom, top; if (aspect_ratio < 1.0){ - left = -this->orthoZoom; - right = this->orthoZoom; - bottom = -this->orthoZoom * ( 1.0f / aspect_ratio ); - top = this->orthoZoom * ( 1.0f / aspect_ratio ); + left = - (this->orthoZoom + this->orthoZoom_offset); + right = (this->orthoZoom + this->orthoZoom_offset); + bottom = -(this->orthoZoom + this->orthoZoom_offset) * ( 1.0f / aspect_ratio ); + top = (this->orthoZoom + this->orthoZoom_offset) * ( 1.0f / aspect_ratio ); } else { - left = -this->orthoZoom * aspect_ratio; - right = this->orthoZoom * aspect_ratio; - bottom = -this->orthoZoom; - top = this->orthoZoom; + left = -(this->orthoZoom + this->orthoZoom_offset) * aspect_ratio; + right = (this->orthoZoom + this->orthoZoom_offset) * aspect_ratio; + bottom = -(this->orthoZoom + this->orthoZoom_offset); + top = (this->orthoZoom + this->orthoZoom_offset); } glOrtho(left, right, bottom, top, -this->farPlane, this->farPlane); } } /** View transformations **/ void CameraNode::viewTransform() { //If first person if (this->cameraType == FIRSTPERSON){ //To do: Make this rotate on a local, orthonormal basis glRotatef(this->rotate->z, 0.0f, 0.0f, 1.0f); //Roll - glRotatef(this->rotate->y, 0.0f, 1.0f, 0.0f); //Pitch - glRotatef(this->rotate->x, 1.0f, 0.0f, 0.0f); //Heading + glRotatef(this->rotate->y, 0.0f, 1.0f, 0.0f); //Heading + glRotatef(this->rotate->x, 1.0f, 0.0f, 0.0f); //Pitch glTranslatef(-this->translate->x, -this->translate->y, -this->translate->z); } else { //If third person - glTranslatef(-((GLfloat)this->panX + (GLfloat)this->panX_offset), -((GLfloat)this->panY + (GLfloat)this->panY_offset), -( (GLfloat)this->distance + (GLfloat)this->distance_offset) ); //Translate along the z axis away from camera - glRotatef((GLfloat)this->twist + (GLfloat)this->twist_offset, (GLfloat)0.0, (GLfloat)0.0, (GLfloat)1.0); //Rotate around z axis (usually by 0) - glRotatef((GLfloat)this->elevation + (GLfloat)this->elevation_offset, (GLfloat)1.0, (GLfloat)0.0, (GLfloat)0.0); //Rotate around x axis - glRotatef((GLfloat)this->azimuth + (GLfloat)this->azimuth_offset, (GLfloat)0.0, (GLfloat)1.0, (GLfloat)0.0); //Rotate around y axis - //To do: Make this rotate on a local, orthonormal basis + //Do third person view transform + //glTranslatef(-((GLfloat)this->panX + (GLfloat)this->panX_offset), -((GLfloat)this->panY + (GLfloat)this->panY_offset), -( (GLfloat)this->distance + (GLfloat)this->distance_offset) ); //Translate along the z axis away from camera + glTranslatef(-(this->panX + this->panX_offset), -(this->panY + this->panY_offset), -( this->distance + this->distance_offset) ); //Translate along the z axis away from camera + glRotatef(this->twist + this->twist_offset, 0.0f, 0.0f, 1.0f); //Rotate around z axis (usually by 0) + glRotatef(this->elevation + this->elevation_offset, 1.0f, 0.0f, 0.0f); //Rotate around x axis + glRotatef(this->azimuth + this->azimuth_offset, 0.0f, 1.0f, 0.0f); //Rotate around y axis + + //Local view transform based on position/rotation of the node glRotatef(this->rotate->z, 0.0f, 0.0f, 1.0f); //Roll - glRotatef(this->rotate->y, 0.0f, 1.0f, 0.0f); //Pitch - glRotatef(this->rotate->x, 1.0f, 0.0f, 0.0f); //Heading + glRotatef(this->rotate->y, 0.0f, 1.0f, 0.0f); //Heading + glRotatef(this->rotate->x, 1.0f, 0.0f, 0.0f); //Pitch glTranslatef(-this->translate->x, -this->translate->y, -this->translate->z); } - - //Call parent viewTransform if (this->parent != NULL) { this->parent->viewTransform(); } } \ No newline at end of file diff --git a/CameraNode.h b/CameraNode.h index a70551e..a5abd9e 100644 --- a/CameraNode.h +++ b/CameraNode.h @@ -1,85 +1,85 @@ /* * Camera.h * OBJViewer * * Created by Leonard Teo on 10-10-06. * Copyright 2010 Leonard Teo. All rights reserved. * */ #ifndef CAMERANODE_H #define CAMERANODE_H #include "Node.h" #include <GL/glew.h> #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/GLUT.h> #else #include <GL/glut.h> #endif enum CameraProjection { PERSPECTIVE, ORTHO }; enum CameraType { POLAR, FIRSTPERSON }; /** * Camera class extends Node */ class CameraNode : public Node { public: //Data Members CameraProjection cameraProjection; CameraType cameraType; //Constructor/Destructor CameraNode(CameraType); ~CameraNode(); //@todo: Should these be private? //Members //Third person camera / polar camera float twist; //Roll float elevation; //Pitch float azimuth; //Heading float distance; //Distance from point of interest (assume local origin) float panX; //Used for panning the camera float panY; + //Orthographic camera + float orthoZoom; //The orthographic zoom factor + + bool perspectiveMode; //Switch between perspective and ortho + //Third person offsets - used for controlling mouse movements where you don't want to write directly to the twist, elevation, azimuth float twist_offset; float elevation_offset; float azimuth_offset; float distance_offset; float panX_offset; float panY_offset; - + float orthoZoom_offset; //Used for handling mouse in and out //Projection settings float fov; //Field of View float nearPlane; //Near clipping plane float farPlane; //Far clipping plane - bool perspectiveMode; //Switch between perspective and ortho - - //Ortho - float orthoZoom; //The orthographic zoom factor - //Methods void setProjection(int width, int height); void viewTransform(); }; #endif diff --git a/LightNode.cpp b/LightNode.cpp new file mode 100644 index 0000000..a3c5af3 --- /dev/null +++ b/LightNode.cpp @@ -0,0 +1,100 @@ +#include "LightNode.h" + + +LightNode::LightNode(GLenum id, LightType type) : Node() +{ + this->type = type; + this->id = id; + this->on = true; + + this->ambient[0] = 1.0f; + this->ambient[1] = 1.0f; + this->ambient[2] = 1.0f; + this->ambient[3] = 1.0f; + + this->diffuse[0] = 1.0f; + this->diffuse[1] = 1.0f; + this->diffuse[2] = 1.0f; + this->diffuse[3] = 1.0f; + + this->specular[0] = 1.0f; + this->specular[1] = 1.0f; + this->specular[2] = 1.0f; + this->specular[3] = 1.0f; + + if (this->type == DIRECTIONAL) + { + //By default directional light shines from z=1 + this->position[0] = 0.0f; + this->position[1] = 0.0f; + this->position[2] = 1.0f; + this->position[3] = 0.0f; + + + } else { + //By default this light is at 0 + this->position[0] = 0.0f; + this->position[1] = 0.0f; + this->position[2] = 0.0f; + this->position[3] = 1.0f; + } + + //By default the light is pointing at positive z (sounds retarded but this is consistent with all the 3D models) + this->spotDirection[0] = 0.0f; + this->spotDirection[1] = 0.0f; + this->spotDirection[2] = 1.0f; + + this->spotCutOff = 45.0f; + +} + + +void LightNode::render(enum RenderType renderType) +{ + + //Do transformations + glPushMatrix(); + glTranslatef(this->translate->x, this->translate->y, this->translate->z); + + //This piece of code is not good because the order of rotation is actually important. + //We need to figure out a way to rotate an entire local coordinate system. + //This should be relatively simple but we'll need to figure it out... + glRotatef(this->rotate->z, 0.0f, 0.0f, 1.0f); + glRotatef(this->rotate->y, 0.0f, 1.0f, 0.0f); + glRotatef(this->rotate->x, 1.0f, 0.0f, 0.0f); + + glScalef(this->scale->x, this->scale->y, this->scale->z); + + //Do lighting + glLightfv(this->id, GL_AMBIENT, this->ambient); + glLightfv(this->id, GL_DIFFUSE, this->diffuse); + glLightfv(this->id, GL_SPECULAR, this->specular); + glLightfv(this->id, GL_POSITION, this->position); + + if (this->type == SPOTLIGHT) + { + glLightf(this->id, GL_SPOT_CUTOFF, this->spotCutOff); + glLightfv(this->id, GL_SPOT_DIRECTION, this->spotDirection); + } + + if (this->on) + { + glEnable(this->id); + } else { + glDisable(this->id); + } + + //Draw children + for (int i=0; i < this->children->size(); i++) + { + this->children->at(i)->render(renderType); + } + + glPopMatrix(); + +} + + +LightNode::~LightNode(void) +{ +} diff --git a/LightNode.h b/LightNode.h new file mode 100644 index 0000000..cdf2e05 --- /dev/null +++ b/LightNode.h @@ -0,0 +1,43 @@ +#ifndef LIGHTNODE_H +#define LIGHTNODE_H + +#include "Node.h" + +#include <GL/glew.h> + +#ifdef __APPLE__ + #include <OpenGL/gl.h> + #include <OpenGL/glu.h> + #include <GLUT/GLUT.h> +#else + #include <GL/glut.h> +#endif + +enum LightType{ + SPOTLIGHT, DIRECTIONAL, POINTLIGHT +}; + +class LightNode : public Node +{ +public: + LightNode(GLenum id, LightType type); + ~LightNode(void); + + LightType type; + GLenum id; + + GLfloat ambient[4]; + GLfloat diffuse[4]; + GLfloat specular[4]; + GLfloat position[4]; + GLfloat spotDirection[3]; + + GLfloat spotCutOff; + + bool on; + + void render(RenderType renderType = ALL_OBJECTS); + +}; + +#endif \ No newline at end of file diff --git a/Material.cpp b/Material.cpp new file mode 100644 index 0000000..77cb748 --- /dev/null +++ b/Material.cpp @@ -0,0 +1,59 @@ +#include "Material.h" + + +Material::Material(void) +{ + //Default material + this->ambient[0] = 0.0f; + this->ambient[1] = 0.0f; + this->ambient[2] = 0.0f; + this->ambient[3] = 1.0f; + + this->diffuse[0] = 0.9f; + this->diffuse[1] = 0.9f; + this->diffuse[2] = 0.9f; + this->diffuse[3] = 1.0f; + + this->specular[0] = 0.8f; + this->specular[1] = 0.8f; + this->specular[2] = 0.8f; + this->specular[3] = 1.0f; + + this->shininess[0] = 5.0f; + +} + +void Material::setAmbient(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) +{ + this->ambient[0] = red; + this->ambient[1] = green; + this->ambient[2] = blue; + this->ambient[3] = alpha; +} +void Material::setDiffuse(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) +{ + this->diffuse[0] = red; + this->diffuse[1] = green; + this->diffuse[2] = blue; + this->diffuse[3] = alpha; +} +void Material::setDiffuseAndAmbient(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) +{ + this->setDiffuse(red, green, blue, alpha); + this->setAmbient(red, green, blue, alpha); +} +void Material::setSpecular(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) +{ + this->specular[0] = red; + this->specular[1] = green; + this->specular[2] = blue; + this->specular[3] = alpha; +} +void Material::setShininess(GLfloat power) +{ + this->shininess[0] = power; +} + +Material::~Material(void) +{ +} diff --git a/Material.h b/Material.h new file mode 100644 index 0000000..281ee26 --- /dev/null +++ b/Material.h @@ -0,0 +1,32 @@ +#ifndef MATERIAL_H +#define MATERIAL_H + +#include <GL/glew.h> + +#ifdef __APPLE__ + #include <OpenGL/gl.h> + #include <OpenGL/glu.h> + #include <GLUT/GLUT.h> +#else + #include <GL/glut.h> +#endif + +class Material +{ +public: + Material(void); + ~Material(void); + + GLfloat ambient[4]; + GLfloat diffuse[4]; + GLfloat specular[4]; + GLfloat shininess[1]; + + void setAmbient(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha = 1.0f); + void setDiffuse(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha = 1.0f); + void setSpecular(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha = 1.0f); + void setDiffuseAndAmbient(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha = 1.0f); + void setShininess(GLfloat power); +}; + +#endif \ No newline at end of file diff --git a/Node.cpp b/Node.cpp index c7065c3..621edf2 100644 --- a/Node.cpp +++ b/Node.cpp @@ -1,72 +1,80 @@ /* * Node.cpp * OBJViewer * * Created by Leonard Teo on 10-10-05. * */ #include "Node.h" //Constructor Node::Node() { this->parent = NULL; this->children = new vector<Node*>; this->scale = new Vector3(1.0f, 1.0f, 1.0f); this->rotate = new Vector3(); this->translate = new Vector3(); this->id = ""; //Blank ID? } //Destructor Node::~Node() { - this->children->clear(); + this->children->clear(); //Clear the vector delete this->children; delete this->scale; delete this->rotate; delete this->translate; delete this; } //Add a child void Node::addChild(Node* child) { //Set the child node's parent as this one child->setParent(this); //Add the child node this->children->push_back(child); } //Set the parent void Node::setParent(Node* parent) { this->parent = parent; } //Abstract method for rendering - must be overloaded by child classes -void Node::render() +void Node::render(RenderType renderType) { for (int i=0; i<this->children->size(); i++) { - this->children->at(i)->render(); + this->children->at(i)->render(renderType); } } //Abstract method for doing view transformations void Node::viewTransform() { - //To do: Make this rotate on a local, orthonormal basis + //Transform view according to local node orientation glRotatef(-this->rotate->z, 0.0f, 0.0f, 1.0f); //Roll - glRotatef(-this->rotate->y, 0.0f, 1.0f, 0.0f); //Pitch - glRotatef(-this->rotate->x, 1.0f, 0.0f, 0.0f); //Heading + glRotatef(-this->rotate->y, 0.0f, 1.0f, 0.0f); //Heading + glRotatef(-this->rotate->x, 1.0f, 0.0f, 0.0f); //Pitch + glTranslatef(-this->translate->x, -this->translate->y, -this->translate->z); if (this->parent != NULL) { this->parent->viewTransform(); } -} \ No newline at end of file +} + +void Node::setTranslation(float x, float y, float z) +{ + this->translate->x = x; + this->translate->y = y; + this->translate->z = z; +} diff --git a/Node.h b/Node.h index c012f90..e662127 100644 --- a/Node.h +++ b/Node.h @@ -1,58 +1,63 @@ /* * Node.h * OBJViewer * * Created by Leonard Teo on 10-10-05. * */ #ifndef NODE_H #define NODE_H #include <vector> #include <string> #include <GL/glew.h> #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/GLUT.h> #else #include <GL/glut.h> #endif #include "Vector3.h" using namespace std; enum NodeType { POLYMESH, CAMERA, LIGHT, TRANSFORM }; +enum RenderType { + OPAQUE_OBJECTS, TRANSPARENT_OBJECTS, ALL_OBJECTS +}; + class Node { public: //Data Members NodeType type; //The type of node this is vector<Node*>* children; //Child nodes Node* parent; //The node's parent string id; //The node's ID so that we can search for a node //Local Transforms Vector3* scale; //Local scaling Vector3* rotate; //Local rotation on x, y, z axes Vector3* translate; //Local translation //Methods Node(); ~Node(); void addChild(Node*); void setParent(Node*); - virtual void render(); + void setTranslation(float x, float y, float z); + virtual void render(RenderType renderType = ALL_OBJECTS); virtual void viewTransform(); }; #endif diff --git a/OBJModel.cpp b/OBJModel.cpp index 8a3529f..7ed2842 100644 --- a/OBJModel.cpp +++ b/OBJModel.cpp @@ -1,378 +1,380 @@ #include "OBJModel.h" using namespace std; //Constructor OBJModel::OBJModel(const char* fileName) { this->init(); this->load(fileName); } //Free memory OBJModel::~OBJModel(void) { //Free all vertices and normals delete [] this->vertices; delete [] this->normals; delete [] this->uvs; delete [] this->index; delete [] this->normalsIndex; delete [] this->uvIndex; delete [] this->vertexArray; delete [] this->normalsArray; delete [] this->uvArray; delete [] this->indexArray; } //General class initialization void OBJModel::init() { this->numVertices = 0; this->numFaces = 0; this->numUVs = 0; this->numNormals = 0; //Set all arrays to null this->vertices = NULL; this->uvs = NULL; this->normals = NULL; this->index = NULL; this->uvIndex = NULL; this->normalsIndex = NULL; this->vertexArray = NULL; this->normalsArray = NULL; this->uvArray = NULL; this->indexArray = NULL; //VBO this->vbo_vertices = 0; this->vbo_normals = 0; this->vbo_uvs = 0; this->vbo_index = 0; } /** * Load the OBJ Model into memory **/ void OBJModel::load(const char* fileName) { char buffer[255]; //Open file for reading ifstream file; file.open(fileName); if (!file.is_open()) { //If file isn't open cout << "Error loading file: " << fileName << endl; return; } else { //First pass of reading the file counts the data while ( !file.eof() ){ //Read the line file.getline(buffer, 255); //Read the line switch(buffer[0]) { //Vertex case 'v': switch(buffer[1]) { case ' ': this->numVertices++; break; case 'n': this->numNormals++; break; case 't': this->numUVs++; break; } break; //Face case 'f': this->numFaces++; break; default: break; } } //end of file //Echo the stats + /* printf("Loading OBJ file\n"); printf("fileName: %s \n", fileName); printf("Vertices: %d \n", this->numVertices); printf("Vertex Normals: %d \n", this->numNormals); printf("Faces: %d \n", this->numFaces); printf("\n"); + */ //Allocate memory for data //Init vertices this->vertices = new Vector3*[this->numVertices]; this->index = new int*[this->numFaces]; //Init normals this->normals = new Vector3*[this->numNormals]; this->normalsIndex = new int*[this->numFaces]; //Triangles //Init UV's this->uvs = new UV*[this->numUVs]; this->uvIndex = new int*[this->numFaces]; //Initialize each of the indices for (int i=0; i<this->numFaces; i++){ this->index[i] = new int[3]; this->normalsIndex[i] = new int[3]; this->uvIndex[i] = new int[3]; for (int j=0; j<3; j++){ this->index[i][j] = 0; this->normalsIndex[i][j] = 0; this->uvIndex[i][j] = 0; } } //Second pass of file to load data file.clear(); //Clear eof status file.seekg(0, ios::beg); //Move cursor to beginning int currentVertex = 0; int currentIndex = 0; int currentNormal = 0; int currentUV = 0; int currentUVIndex = 0; int currentNormalIndex = 0; while (!file.eof()){ //Read line file.getline(buffer, 255); switch (buffer[0]){ //Vertex case 'v': switch(buffer[1]){ case ' ': //Create new vertex this->vertices[currentVertex] = new Vector3(); sscanf(buffer, "v %f %f %f", &this->vertices[currentVertex]->x, &this->vertices[currentVertex]->y, &this->vertices[currentVertex]->z); currentVertex++; break; case 'n': //Create new vertex normal this->normals[currentNormal] = new Vector3(); sscanf(buffer, "vn %f %f %f", &this->normals[currentNormal]->x, &this->normals[currentNormal]->y, &this->normals[currentNormal]->z); currentNormal++; break; case 't': //Create new UV this->uvs[currentUV] = new UV(); sscanf(buffer, "vt %f %f", &this->uvs[currentUV]->u, &this->uvs[currentUV]->v); currentUV++; break; } break; case 'f': sscanf(buffer, "f %d/%d/%d %d/%d/%d %d/%d/%d", &this->index[currentIndex][0], &this->uvIndex[currentUVIndex][0], &this->normalsIndex[currentNormalIndex][0], &this->index[currentIndex][1], &this->uvIndex[currentUVIndex][1], &this->normalsIndex[currentNormalIndex][1], &this->index[currentIndex][2], &this->uvIndex[currentUVIndex][2], &this->normalsIndex[currentNormalIndex][2]); currentIndex++; currentNormalIndex++; currentUVIndex++; break; } } //end of file //Release file pointer file.close(); } //decrement all indices to cater for OpenGL (OBJ indices start at 1) for(int i = 0; i < this->numFaces; i++) { for(int j=0; j<3; j++){ this->index[i][j]--; this->normalsIndex[i][j]--; this->uvIndex[i][j]--; } } //Prepare the arrays for drawing this->prepArrays(); } /** Takes the vertex, normals and texture coords and turns them into straight march arrays for OpenGL to render **/ void OBJModel::prepArrays() { //Initialize the arrays this->vertexArray = new GLfloat[this->numFaces *3 * 3]; //3 vertices to a face, 3 floats to a vertex this->normalsArray = new GLfloat[this->numFaces *3 * 3]; this->indexArray = new GLuint[this->numFaces * 3]; this->uvArray = new GLfloat[this->numFaces * 3 * 2]; //3 vertices to a face, 2 floats to a UV //Turn index into a straight march int numElements = this->numFaces * 3; for (int i=0; i<numElements; i++) { this->indexArray[i] = i; } //Figure out vertices, normals and UVs for (int face = 0; face < this->numFaces; face++) { //Get vertex numbers int v1, v2, v3; v1 = this->index[face][0]; v2 = this->index[face][1]; v3 = this->index[face][2]; //Get Normal numbers int n1, n2, n3; n1 = this->normalsIndex[face][0]; n2 = this->normalsIndex[face][1]; n3 = this->normalsIndex[face][2]; //Get UVs int uv1, uv2, uv3; uv1 = this->uvIndex[face][0]; uv2 = this->uvIndex[face][1]; uv3 = this->uvIndex[face][2]; //Element 1 this->uvArray[6*face] = (GLfloat) this->uvs[uv1]->u; this->uvArray[6*face + 1] = (GLfloat) this->uvs[uv1]->v; this->normalsArray[9*face] = (GLfloat) this->normals[n1]->x; this->normalsArray[9*face + 1] = (GLfloat) this->normals[n1]->y; this->normalsArray[9*face + 2] = (GLfloat) this->normals[n1]->z; this->vertexArray[9*face] = (GLfloat) this->vertices[v1]->x; this->vertexArray[9*face + 1] = (GLfloat) this->vertices[v1]->y; this->vertexArray[9*face + 2] = (GLfloat) this->vertices[v1]->z; //Element 2 this->uvArray[6*face + 2] = (GLfloat) this->uvs[uv2]->u; this->uvArray[6*face + 3] = (GLfloat) this->uvs[uv2]->v; this->normalsArray[9*face + 3] = (GLfloat) this->normals[n2]->x; this->normalsArray[9*face + 4] = (GLfloat) this->normals[n2]->y; this->normalsArray[9*face + 5] = (GLfloat) this->normals[n2]->z; this->vertexArray[9*face + 3] = (GLfloat) this->vertices[v2]->x; this->vertexArray[9*face + 4] = (GLfloat) this->vertices[v2]->y; this->vertexArray[9*face + 5] = (GLfloat) this->vertices[v2]->z; //Element 3 this->uvArray[6*face + 4] = (GLfloat) this->uvs[uv3]->u; this->uvArray[6*face + 5] = (GLfloat) this->uvs[uv3]->v; this->normalsArray[9*face + 6] = (GLfloat)this->normals[n3]->x; this->normalsArray[9*face + 7] = (GLfloat)this->normals[n3]->y; this->normalsArray[9*face + 8] = (GLfloat)this->normals[n3]->z; this->vertexArray[9*face + 6] = (GLfloat)this->vertices[v3]->x; this->vertexArray[9*face + 7] = (GLfloat)this->vertices[v3]->y; this->vertexArray[9*face + 8] = (GLfloat)this->vertices[v3]->z; } //Release all the object memory - we only need the arrays delete [] this->vertices; delete [] this->normals; delete [] this->uvs; delete [] this->index; delete [] this->normalsIndex; delete [] this->uvIndex; //this->debugArrays(); //Check vertex buffer object extension if (glewGetExtension("GL_ARB_vertex_buffer_object")) { - cout << "Vertex buffer objects supported!" << endl; + //cout << "Vertex buffer objects supported!" << endl; //Load vertices glGenBuffers(1, &this->vbo_vertices); //Get name/ID glBindBuffer(GL_ARRAY_BUFFER, this->vbo_vertices); //Bind the buffer to the name glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*this->numFaces*3*3, this->vertexArray, GL_STATIC_DRAW); //Load normals glGenBuffers(1, &this->vbo_normals); //Get name/ID glBindBuffer(GL_ARRAY_BUFFER, this->vbo_normals); //Bind the buffer to the name glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*this->numFaces*3*3, this->normalsArray, GL_STATIC_DRAW); //Load UVs glGenBuffers(1, &this->vbo_uvs); //Get name/ID glBindBuffer(GL_ARRAY_BUFFER, this->vbo_uvs); //Bind the buffer to the name glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*this->numFaces*3*2, this->uvArray, GL_STATIC_DRAW); //Load index glGenBuffers(1, &this->vbo_index); //Get name/ID glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->vbo_index); //Bind the buffer to the name glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*this->numFaces*3, this->indexArray, GL_STATIC_DRAW_ARB); //Clear bind buffers glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - cout << "Loaded model into GPU memory" << endl; + //cout << "Loaded model into GPU memory" << endl; } } //Show all the array data void OBJModel::debugArrays() { FILE *file = fopen("debug.txt", "w"); if (file == NULL) { printf("Couldn't open debug file."); return; } fprintf(file, "Element Index: \n"); for (int face=0; face < this->numFaces; face++) { fprintf(file, "%d %d %d \n", this->indexArray[3*face], this->indexArray[3*face + 1], this->indexArray[3*face + 2]); } fprintf(file, "\nVertices: \n"); for (int face=0; face < this->numFaces; face++) { fprintf(file, "%f %f %f %f %f %f %f %f %f \n", this->vertexArray[3*face], this->vertexArray[3*face + 1], this->vertexArray[3*face + 2], this->vertexArray[3*face+3], this->vertexArray[3*face + 4], this->vertexArray[3*face + 5], this->vertexArray[3*face+6], this->vertexArray[3*face + 7], this->vertexArray[3*face + 8] ); } fprintf(file, "\nNormals: \n"); for (int face=0; face < this->numFaces; face++) { fprintf(file, "%f %f %f %f %f %f %f %f %f \n", this->normalsArray[3*face], this->normalsArray[3*face + 1], this->normalsArray[3*face + 2], this->normalsArray[3*face+3], this->normalsArray[3*face + 4], this->normalsArray[3*face + 5], this->normalsArray[3*face+6], this->normalsArray[3*face + 7], this->normalsArray[3*face + 8] ); } fclose(file); } diff --git a/OBJViewer.cpp b/OBJViewer.cpp index 23d4434..2cb93ec 100644 --- a/OBJViewer.cpp +++ b/OBJViewer.cpp @@ -1,835 +1,681 @@ /** OBJ Viewer **/ //STD libraries #include <iostream> #include <string> //OpenGL libraries #include <GL/glew.h> #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/GLUT.h> #else #include <GL/glut.h> #endif //Engine libraries #include "OBJModel.h" #include "MyBitmap.h" #include "Node.h" #include "TransformNode.h" #include "PolyMeshNode.h" #include "Texture.h" #include "Vector3.h" #include "CameraNode.h" #include "PolarCamera.h" using namespace std; //Default Screen Size const int WIDTH = 640; const int HEIGHT = 480; /** Global Variables **/ //Temporary screen width and height int width = WIDTH; int height = HEIGHT; //Mouse position int mouse_x; int mouse_y; int mouse_down_x; //Mouse position when a user clicks int mouse_down_y; //Mouse clicks states bool left_mouse_down = false; bool middle_mouse_down = false; bool right_mouse_down = false; //Model type int model = 0; //Show Wireframe bool show_wireframe = false; bool shaded_mode = true; -//Camera - Polar view -PolarCamera* camera = new PolarCamera(); - //Scene Graph Camera CameraNode* sgCamera; //Temporary variables to facilitate Polar camera float azimuth_change = 0; float twist_change = 0; float elevation_change = 0; float cam_distance_change = 0.0; //Panning temporary variables float pan_x_down = 0; //When the pan button is pushed, record this float pan_y_down = 0; float pan_z_down = 0; float pan_x_change = 0; float pan_y_change = 0; //Orthographic zooming temporary variable float ortho_zoom_change = 0; - - //Texture MyBitmap* texture; static GLuint texName; //Scene Graph Node* rootNode; //Calculating fps int frame = 0, time, timebase=0; float fps=0.0f; int font=(int)GLUT_BITMAP_8_BY_13; char s[30]; //For testing PolyMeshNode* humveeNode; /** Draw a 24x24 grid **/ static void grid(int scale = 1) { //Turn off lighting for grid glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); //Start drawing lines glBegin(GL_LINES); glColor3f(0.5, 0.5, 0.5); for (int x=-12; x<=12; x++){ if (x != 0){ glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(-12*scale)); glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(12*scale)); } } for (int z=-12; z<=12; z++){ if (z != 0){ glVertex3f((GLfloat)(-12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); glVertex3f((GLfloat)(12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); } } glEnd(); //Make sure the lines at the origin are nice and different /* glBegin(GL_LINES); glColor3f(0.75, 0.75, 0.75); glVertex3f(0, 0, (GLfloat)(-12*scale)); glVertex3f(0, 0, (GLfloat)(12*scale)); glVertex3f((GLfloat)(-12*scale), 0, 0); glVertex3f((GLfloat)(12*scale), 0, 0); glEnd(); */ //Draw axis glBegin(GL_LINES); //x axis should be red and pointing to positive x glColor3f(1.0, 0.0, 0.0); glVertex3f(0.0, 0.0, 0.0); glVertex3f(12*scale, 0.0, 0.0); glEnd(); //Draw cone glPushMatrix(); glTranslatef(12*scale, 0.0, 0.0); glRotatef(90, 0.0, 1.0, 0.0); glutSolidCone(0.2, 0.75, 8, 3); glPopMatrix(); glBegin(GL_LINES); //y axis glColor3f(0.0, 1.0, 0.0); glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 12*scale, 0.0); glEnd(); //Draw cone glPushMatrix(); glTranslatef(0.0, 12*scale, 0.0); glRotatef(-90, 1.0, 0.0, 0.0); glutSolidCone(0.2, 0.75, 8, 3); glPopMatrix(); glBegin(GL_LINES); //z axis glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 0.0, 12*scale); glEnd(); //Draw cone glPushMatrix(); glTranslatef(0.0, 0.0, 12*scale); glutSolidCone(0.2, 0.75, 8, 3); glPopMatrix(); glFlush(); //Turn lighting back on glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); } static void draw_models() { //Draw using scene graph rootNode->render(); } void drawText(char* string) { char* p; for (p=string; *p; p++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *p); } } /** Calculate and display FPS **/ static void profiler() { glDisable(GL_TEXTURE_2D); //Calculate FPS frame++; //Increment number of frames time = glutGet(GLUT_ELAPSED_TIME); //Get current time //Time is current time, timebase is last time since we took a benchmark if ((time - timebase) > 500) { //Do this every x milliseconds float fps = 1000* (float)frame / (float)(time-timebase); sprintf(s,"FPS: %4.2f", fps ); timebase = time; //Set timebase to current time frame = 0; //Reset number of frames } glColor3f(1.0f, 1.0f, 1.0f); glWindowPos2i(5, 5); drawText(s); glEnable(GL_TEXTURE_2D); } /** Display function **/ static void display() { //Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //Call scene graph camera sgCamera->viewTransform(); - /** - Camera setup - **/ - - //Translate & Rotate Polar Views - /* - glTranslatef(-(GLfloat)(camera->point_of_interest->x + pan_x_change), (GLfloat)(camera->point_of_interest->y + pan_y_change), -((GLfloat)camera->distance + (GLfloat)cam_distance_change)); //Translate along the z axis away from camera - glRotatef((GLfloat)camera->twist + (GLfloat)twist_change, (GLfloat)0.0, (GLfloat)0.0, (GLfloat)1.0); //Rotate around z axis (usually by 0) - glRotatef((GLfloat)camera->elevation + (GLfloat)elevation_change, (GLfloat)1.0, (GLfloat)0.0, (GLfloat)0.0); //Rotate around x axis - glRotatef((GLfloat)camera->azimuth + (GLfloat)azimuth_change, (GLfloat)0.0, (GLfloat)1.0, (GLfloat)0.0); //Rotate around y axis - */ - //Draw grid grid(); //Wireframe switching //If shaded mode, draw the model with shading, else only draw the wireframe if (shaded_mode){ //Setup polygon offset for drawing wire on shaded glPolygonOffset(1.0, 1.0); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glColor3f(1.0, 1.0, 1.0); //Draw the obj model draw_models(); glDisable(GL_POLYGON_OFFSET_FILL); //If show wireframe, render the wireframe on top of shaded object if (show_wireframe){ glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glColor3f(0.0, 0.0, 0.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); } } else { //Wireframe only glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); glDisable(GL_CULL_FACE); glColor3f(1.0, 1.0, 1.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE); } profiler(); glutSwapBuffers(); } /** Sets the projection **/ static void set_projection() { + glViewport(0, 0, width, height); sgCamera->setProjection(width, height); - /* - glViewport(0, 0, (GLsizei) width, (GLsizei) height); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - //Perspective mode or ortho - float aspect_ratio = (float)width / (float)height; - if (camera->perspective_mode){ - gluPerspective(camera->fov, GLfloat(aspect_ratio), camera->near_plane, camera->far_plane); - } else { - //Keep aspect ratio - float left, right, bottom, top, temp_ortho_zoom; - temp_ortho_zoom = camera->ortho_zoom + ortho_zoom_change; - - if (aspect_ratio < 1.0){ - left = -temp_ortho_zoom; - right = temp_ortho_zoom; - bottom = -temp_ortho_zoom * ( 1.0f / aspect_ratio ); - top = temp_ortho_zoom * ( 1.0f / aspect_ratio ); - } else { - left = -temp_ortho_zoom * aspect_ratio; - right = temp_ortho_zoom * aspect_ratio; - bottom = -temp_ortho_zoom; - top = temp_ortho_zoom; - } - glOrtho(left, right, bottom, top, -camera->far_plane, camera->far_plane); - } - */ } /** Reshape function **/ static void reshape(int new_width, int new_height) { //Set Global Variables width = new_width; height = new_height; set_projection(); //sgCamera->setProjection(width, height); } /** Keyboard Input **/ static void keyboard_func(unsigned char key, int mx, int my) { switch (key) { - //Camera Motion for Assignment - case 'u': - camera->point_of_interest->y -= 0.02f; - glutPostRedisplay(); - break; - case 'd': - camera->point_of_interest->y += 0.02f; - glutPostRedisplay(); - break; - case 'l': - camera->point_of_interest->x -= 0.02f; - glutPostRedisplay(); - break; - case 'r': - camera->point_of_interest->x += 0.02f; - glutPostRedisplay(); - break; - case 'f': - camera->distance -= 0.2f; - glutPostRedisplay(); - break; - case 'b': - camera->distance += 0.2f; - glutPostRedisplay(); - break; //Views case 'c': //Reset views //Destroy and reinitialize camera - /* - delete camera; - camera = new PolarCamera(); - set_projection(); - */ + break; case 'w': //Show Wireframe show_wireframe = show_wireframe == false ? true : false; break; case 's': //Shaded Model shaded_mode = shaded_mode == false ? true : false; break; case 'p': //Perspective - camera->perspective_mode = true; + sgCamera->perspectiveMode = true; set_projection(); break; case 'o': //Ortho - camera->perspective_mode = false; - set_projection(); - break; - case 'z': //Zoom forward - if (camera->perspective_mode){ - camera->fov -= 1.5f; - } else { - camera->ortho_zoom -= 0.1f; - } - set_projection(); - break; - case 'Z': //Zoom back - if (camera->perspective_mode){ - camera->fov += 1.5f; - } else { - camera->ortho_zoom += 0.1f; - } + sgCamera->perspectiveMode = false; set_projection(); break; + //Alternative zoom case '+': //Zoom forward - if (camera->perspective_mode){ - camera->fov -= 1.5f; + if (sgCamera->perspectiveMode){ + sgCamera->fov -= 1.5f; } else { - camera->ortho_zoom -= 0.1f; + sgCamera->orthoZoom -= 0.1f; } set_projection(); break; case '-': //Zoom back - if (camera->perspective_mode){ - camera->fov += 1.5f; + if (sgCamera->perspectiveMode){ + sgCamera->fov += 1.5f; } else { - camera->ortho_zoom += 0.1f; + sgCamera->orthoZoom += 0.1f; } set_projection(); break; - //Models - case '1': - model = 0; - break; - case '2': - model = 1; - break; - case '3': - model = 2; - break; - case '4': - model = 3; - break; - case '5': - model = 4; - break; - case '6': - model = 5; - break; - case '7': - model = 6; - break; - case '8': - model = 7; - break; - //Exit case 27: exit(0); } glutPostRedisplay(); } /** Function Keys **/ static void functionKeys(int key, int mx, int my) { } /** Mouse Clicks **/ static void mouse_clicks(int button, int state, int mx, int my) { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) { left_mouse_down = true; //Set mouse down state to true mouse_down_x = mx; //Record screen position of mouse when user clicked left button mouse_down_y = my; //cout << "Left mouse button clicked at:" << mx << ", " << my << endl; } else { left_mouse_down = false; //Add changes to camera sgCamera->azimuth += sgCamera->azimuth_offset; sgCamera->elevation += sgCamera->elevation_offset; sgCamera->azimuth_offset = 0.0f; sgCamera->elevation_offset = 0.0f; } break; case GLUT_RIGHT_BUTTON: //Move camera forward and back if (state == GLUT_DOWN) { right_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { right_mouse_down = false; //Reset camera distance offset sgCamera->distance += sgCamera->distance_offset; sgCamera->distance_offset = 0.0f; - - //Reset distance deltas - camera->distance += cam_distance_change; - cam_distance_change = 0; //Ortho - camera->ortho_zoom += ortho_zoom_change; + sgCamera->orthoZoom += ortho_zoom_change; ortho_zoom_change = 0; } break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_DOWN) { middle_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { middle_mouse_down = false; sgCamera->panX += sgCamera->panX_offset; sgCamera->panX_offset = 0.0f; sgCamera->panY += sgCamera->panY_offset; sgCamera->panY_offset = 0.0f; - - //Reset panning deltas - camera->point_of_interest->x += pan_x_change; - camera->point_of_interest->y += pan_y_change; - pan_x_change = 0; - pan_y_change = 0; } break; } } /** Mouse Movement **/ static void mouse_move(int mx, int my) { //Only bother processing if mouse button is pressed //Left Mouse Button - Orbit if (left_mouse_down){ sgCamera->azimuth_offset = -(float(mouse_down_x) - float(mx)) / float(width) * 90; sgCamera->elevation_offset = -(float(mouse_down_y) - float(my)) / float(height) * 90; } //Right Mouse Button - Dolly if (right_mouse_down){ if (sgCamera->perspectiveMode) { sgCamera->distance_offset = (float(mouse_down_x) - float(mx)) / float(width) * 10; } else { sgCamera->distance_offset = (float(mouse_down_x) - float(mx)) / float(width); sgCamera->setProjection(width, height); } - if (camera->perspective_mode){ - cam_distance_change = (float(mouse_down_x) - float(mx)) / float(width) * 10; - } else { - ortho_zoom_change = (float(mouse_down_x) - float(mx)) / float(width); - set_projection(); - } } //Middle Mouse Button - Panning if (middle_mouse_down){ sgCamera->panX_offset = (float(mouse_down_x) - float(mx)) / float(width) * 5; sgCamera->panY_offset = -(float(mouse_down_y) - float(my)) / float(height) * 5; } //Force redisplay if (left_mouse_down || middle_mouse_down || right_mouse_down){ glutPostRedisplay(); } } /** Enable lighting & materials **/ static void lighting() { glShadeModel(GL_SMOOTH); //glShadeModel(GL_FLAT); //Setup Material GLfloat mat_ambient[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_diffuse[] = {(GLfloat)0.9, (GLfloat)0.9, (GLfloat)0.9, (GLfloat)1.0}; GLfloat mat_specular[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_shininess[] = {(GLfloat)50}; glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); //Setup Light(s) GLfloat light_position[] = {30.0, 30.0, 30.0, 0.0}; GLfloat white_light[] = {1.0, 1.0, 1.0, 1.0}; glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light); glLightfv(GL_LIGHT0, GL_SPECULAR, white_light); //Setup Ambient Light //GLfloat lmodel_ambient[] = {(GLfloat)0.2, (GLfloat)0.2, (GLfloat)0.2, (GLfloat)1.0}; //Turn on lighting glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); } /** Clear out the screen **/ static void init() { //Backface culling glEnable(GL_CULL_FACE); glEnable(GL_TEXTURE_2D); glClearColor(0.0, 0.0, 0.0, 0.0); //Load models - /* - uhtiger = new OBJModel("models/uhtiger.obj"); + + OBJModel* uhtiger = new OBJModel("models/uhtiger.obj"); PolyMeshNode* uhTigerNode = new PolyMeshNode(); uhTigerNode->attachModel(uhtiger); Texture* uhTigerTexture = new Texture("textures/uhtiger.bmp"); uhTigerNode->attachTexture(uhTigerTexture); uhTigerNode->translate->z = 5.0f; - m1abrams = new OBJModel("models/m1abrams.obj"); + OBJModel* m1abrams = new OBJModel("models/m1abrams.obj"); PolyMeshNode* m1AbramsNode = new PolyMeshNode(); m1AbramsNode->attachModel(m1abrams); Texture* m1AbramsTexture = new Texture("textures/M1_ABRAM.bmp"); m1AbramsNode->attachTexture(m1AbramsTexture); m1AbramsNode->translate->z = -5.0f; m1AbramsNode->translate->x = -15.0f; - */ + OBJModel* humveehardtop = new OBJModel("models/humveehardtop.obj"); humveeNode = new PolyMeshNode(); humveeNode->attachModel(humveehardtop); Texture* humveeTexture = new Texture("textures/humveehardtop.bmp"); humveeNode->attachTexture(humveeTexture); humveeNode->rotate->y = -90; - PolyMeshNode* humveeNode2 = new PolyMeshNode(); - humveeNode2->attachModel(humveehardtop); - humveeNode2->attachTexture(humveeTexture); - humveeNode2->translate->x = -20; - humveeNode2->rotate->y = 90; - - PolyMeshNode* humveeNode3 = new PolyMeshNode(); - humveeNode3->attachModel(humveehardtop); - humveeNode3->attachTexture(humveeTexture); - humveeNode3->translate->x = -20; //Scene Graph rootNode = new Node(); - rootNode->addChild(humveeNode); - humveeNode->addChild(humveeNode2); - humveeNode2->addChild(humveeNode3); - //10 tanks - /* - for (int x=-10; x<=10; x++) + //121 tanks + + for (int x=-10; x<10; x++) { - for (int z=-10; z<=10; z++) + for (int z=-10; z<10; z++) { TransformNode* transform = new TransformNode(TRANSLATE); transform->translate->x = x*20; transform->translate->z = z*20; transform->addChild(m1AbramsNode); rootNode->addChild(transform); } } - */ - - //Create a camera and attach to root node - sgCamera = new CameraNode(FIRSTPERSON); - sgCamera->translate->x = -10.0f; - sgCamera->translate->z = 10.0f; - sgCamera->translate->y = 2.0f; - sgCamera->rotate->y = 45; - //rootNode->addChild(sgCamera); + sgCamera = new CameraNode(POLAR); sgCamera->distance = 30.0f; - sgCamera->azimuth = -180.0f; + sgCamera->azimuth = 0.0f; sgCamera->elevation = 40.0f; - humveeNode3->addChild(sgCamera); + //Set up lighting lighting(); //Anti-Aliasing - /* + glEnable (GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glLineWidth (1); - */ + } /** Main function **/ int main(int argc, char** argv) { //Get current directory cout << "Firing up OBJViewer" << endl; cout << "===================" << endl << endl; cout << "Camera Motion " << endl; cout << "Orbit: Left click and drag mouse" << endl; cout << "Panning: Middle click and drag mouse" << endl; cout << "Dolly: Right click and drag mouse" << endl << endl; cout << "Viewport Controls " << endl; cout << "w: Toggle wireframe" << endl; cout << "s: Toggle shaded mode" << endl; cout << "p: Perspective mode" << endl; cout << "o: Orthographic mode" << endl; cout << "+ or z: Zoom in" << endl; cout << "- or Z(shift-z): Zoom out" << endl; cout << "c: Reset view" << endl << endl; cout << "Escape: Quit" << endl; glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 100); glutCreateWindow("OBJViewer Test - Leonard Teo"); //Initialize GLEW GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); exit(1); } fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard_func); glutSpecialFunc(functionKeys); glutMouseFunc(mouse_clicks); glutMotionFunc(mouse_move); glutIdleFunc(display); //Set idle function to force refresh glutMainLoop(); - //Cleanup - - delete camera; - exit(0); } \ No newline at end of file diff --git a/PolyMeshNode.cpp b/PolyMeshNode.cpp index 918922f..ee8f722 100644 --- a/PolyMeshNode.cpp +++ b/PolyMeshNode.cpp @@ -1,180 +1,230 @@ /* * PolyMesh.cpp * OBJViewer * * Created by Leonard Teo on 10-10-05. * */ #include "PolyMeshNode.h" //Constructor PolyMeshNode::PolyMeshNode() : Node() { this->mesh = NULL; this->texture = NULL; + this->material = NULL; } //Destructor PolyMeshNode::~PolyMeshNode() { delete this->mesh; delete this->texture; delete this; } //attachModel void PolyMeshNode::attachModel(OBJModel* model) { this->mesh = model; } //attachTexture void PolyMeshNode::attachTexture(Texture* texture) { this->texture = texture; } +//Attach material +void PolyMeshNode::attachMaterial(Material* material) +{ + this->material = material; +} + void PolyMeshNode::draw() { //Load texture if (this->texture != NULL) { glBindTexture(GL_TEXTURE_2D, this->texture->textureID); } + //Load material + if (this->material != NULL) + { + glMaterialfv(GL_FRONT, GL_AMBIENT, this->material->ambient); + glMaterialfv(GL_FRONT, GL_DIFFUSE, this->material->diffuse); + glMaterialfv(GL_FRONT, GL_SPECULAR, this->material->specular); + glMaterialfv(GL_FRONT, GL_SHININESS, this->material->shininess); + } + //Check vertex buffer object extension if (glewGetExtension("GL_ARB_vertex_buffer_object")) { //Load vertices glBindBuffer(GL_ARRAY_BUFFER, this->mesh->vbo_vertices); glVertexPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0)); glEnableClientState(GL_VERTEX_ARRAY); //Load normals glBindBuffer(GL_ARRAY_BUFFER, this->mesh->vbo_normals); glNormalPointer(GL_FLOAT, 0, BUFFER_OFFSET(0)); glEnableClientState(GL_NORMAL_ARRAY); //Load UVs glBindBuffer(GL_ARRAY_BUFFER, this->mesh->vbo_uvs); glTexCoordPointer(2, GL_FLOAT, 0, BUFFER_OFFSET(0)); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->mesh->vbo_index); glDrawElements(GL_TRIANGLES, 3*this->mesh->numFaces, GL_UNSIGNED_INT, BUFFER_OFFSET(0)); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } else { //Drawing with vertex arrays glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointer(3, GL_FLOAT, 0, this->mesh->vertexArray); glNormalPointer(GL_FLOAT, 0, this->mesh->normalsArray); glTexCoordPointer(2, GL_FLOAT, 0, this->mesh->uvArray); glDrawElements(GL_TRIANGLES, 3*this->mesh->numFaces, GL_UNSIGNED_INT, this->mesh->indexArray); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } /* //Old immediate mode drawing code glBegin(GL_TRIANGLES); for (int face = 0; face < this->numFaces; face++) { //Draw the vertex at each of the vertex numbders glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][0]]->u, (GLfloat)this->uvs[this->uvIndex[face][0]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][0]]->x, (GLfloat)this->normals[this->normalsIndex[face][0]]->y, (GLfloat)this->normals[this->normalsIndex[face][0]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][0]]->x, (GLfloat)this->vertices[this->index[face][0]]->y, (GLfloat)this->vertices[this->index[face][0]]->z); glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][1]]->u, (GLfloat)this->uvs[this->uvIndex[face][1]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][1]]->x, (GLfloat)this->normals[this->normalsIndex[face][1]]->y, (GLfloat)this->normals[this->normalsIndex[face][1]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][1]]->x, (GLfloat)this->vertices[this->index[face][1]]->y, (GLfloat)this->vertices[this->index[face][1]]->z); glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][2]]->u, (GLfloat)this->uvs[this->uvIndex[face][2]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][2]]->x, (GLfloat)this->normals[this->normalsIndex[face][2]]->y, (GLfloat)this->normals[this->normalsIndex[face][2]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][2]]->x, (GLfloat)this->vertices[this->index[face][2]]->y, (GLfloat)this->vertices[this->index[face][2]]->z); /* Non-Optimized code for debugging //Get vertex numbers int v1, v2, v3; v1 = this->index[face][0]; v2 = this->index[face][1]; v3 = this->index[face][2]; //Get Normal numbers int n1, n2, n3; n1 = this->normalsIndex[face][0]; n2 = this->normalsIndex[face][1]; n3 = this->normalsIndex[face][2]; //Get UVs int uv1, uv2, uv3; uv1 = this->uvIndex[face][0]; uv2 = this->uvIndex[face][1]; uv3 = this->uvIndex[face][2]; //Draw the vertex at each of the vertex numbders glTexCoord2f((GLfloat)this->uvs[uv1]->u, (GLfloat)this->uvs[uv1]->v); glNormal3f((GLfloat)this->normals[n1]->x, (GLfloat)this->normals[n1]->y, (GLfloat)this->normals[n1]->z); glVertex3f((GLfloat)this->vertices[v1]->x, (GLfloat)this->vertices[v1]->y, (GLfloat)this->vertices[v1]->z); glTexCoord2f((GLfloat)this->uvs[uv2]->u, (GLfloat)this->uvs[uv2]->v); glNormal3f((GLfloat)this->normals[n2]->x, (GLfloat)this->normals[n2]->y, (GLfloat)this->normals[n2]->z); glVertex3f((GLfloat)this->vertices[v2]->x, (GLfloat)this->vertices[v2]->y, (GLfloat)this->vertices[v2]->z); glTexCoord2f((GLfloat)this->uvs[uv3]->u, (GLfloat)this->uvs[uv3]->v); glNormal3f((GLfloat)this->normals[n3]->x, (GLfloat)this->normals[n3]->y, (GLfloat)this->normals[n3]->z); glVertex3f((GLfloat)this->vertices[v3]->x, (GLfloat)this->vertices[v3]->y, (GLfloat)this->vertices[v3]->z); */ /* } glEnd(); */ } -void PolyMeshNode::render() +void PolyMeshNode::render(enum RenderType renderType) { //Draw this glPushMatrix(); - glTranslatef((GLfloat)this->translate->x, (GLfloat)this->translate->y, (GLfloat)this->translate->z); + glTranslatef(this->translate->x, this->translate->y, this->translate->z); //This piece of code is not good because the order of rotation is actually important. //We need to figure out a way to rotate an entire local coordinate system. //This should be relatively simple but we'll need to figure it out... - glRotatef((GLfloat)this->rotate->z, (GLfloat)0.0f, (GLfloat)0.0f, (GLfloat)1.0f); - glRotatef((GLfloat)this->rotate->y, (GLfloat)0.0f, (GLfloat)1.0f, (GLfloat)0.0f); - glRotatef((GLfloat)this->rotate->x, (GLfloat)1.0f, (GLfloat)0.0f, (GLfloat)0.0f); + glRotatef(this->rotate->z, 0.0f, 0.0f, 1.0f); + glRotatef(this->rotate->y, 0.0f, 1.0f, 0.0f); + glRotatef(this->rotate->x, 1.0f, 0.0f, 0.0f); - glScalef((GLfloat)this->scale->x, (GLfloat)this->scale->y, (GLfloat)this->scale->z); + glScalef(this->scale->x, this->scale->y, this->scale->z); + + //Drawing + + //Figure out if this is an opaque or transparent object, and draw appropriately + if (renderType == ALL_OBJECTS) + { + this->draw(); + } else { + if (this->material != NULL) + { + //Check material + if (this->material->diffuse[3] < 1.0f || this->material->ambient[3] < 1.0f) + { + //If there is transparency + + //Check the render type. If transparent, draw + if (renderType == TRANSPARENT_OBJECTS) + { + this->draw(); + } + } else { + //If there is no transparency + if (renderType == OPAQUE_OBJECTS) + { + this->draw(); + } + } + + } else { + //No material -- assume that it is opaque, so draw + this->draw(); + } + + } + - this->draw(); //Draw children for (int i=0; i < this->children->size(); i++) { - this->children->at(i)->render(); + this->children->at(i)->render(renderType); } glPopMatrix(); } \ No newline at end of file diff --git a/PolyMeshNode.h b/PolyMeshNode.h index 2ce8a89..e332a02 100644 --- a/PolyMeshNode.h +++ b/PolyMeshNode.h @@ -1,54 +1,58 @@ /* * PolyMesh.h * OBJViewer * * Created by Leonard Teo on 10-10-05. * */ #ifndef POLYMESHNODE_H #define POLYMESHNODE_H #include "Node.h" #include "OBJModel.h" #include "Texture.h" +#include "Material.h" #include <GL\glew.h> #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/GLUT.h> #else #include <GL/glut.h> #endif #define BUFFER_OFFSET(bytes) ((GLubyte*) NULL + (bytes)) class PolyMeshNode : public Node { public: //Constructor/Destructor PolyMeshNode(); ~PolyMeshNode(); //Attach model - note that this class does NOT load OBJModels. It attaches them so that you can have instances of models void attachModel(OBJModel* model); //Attach texture void attachTexture(Texture* texture); + void attachMaterial(Material* material); + //Draw the polygons using OpenGL calls void draw(); //Scene graph rendering call - void render(); + void render(RenderType renderType = ALL_OBJECTS); //Data members OBJModel* mesh; Texture* texture; + Material* material; }; #endif diff --git a/TransformNode.cpp b/TransformNode.cpp index f45f5ce..403edcc 100644 --- a/TransformNode.cpp +++ b/TransformNode.cpp @@ -1,50 +1,50 @@ /* * TransformNode.cpp * Scene graph node for handling transformations * * Created by Leonard Teo on 10-10-10. * Copyright 2010 Leonard Teo. All rights reserved. * */ #include "TransformNode.h" TransformNode::TransformNode(TransformType transformType) { this->type = TRANSFORM; this->transformType = transformType; } TransformNode::~TransformNode() { } //Do all translations then render child nodes -void TransformNode::render() +void TransformNode::render(enum RenderType renderType) { //Remember where we are glPushMatrix(); switch (this->transformType) { case TRANSLATE: glTranslatef((GLfloat)this->translate->x, (GLfloat)this->translate->y, (GLfloat)this->translate->z); break; case ROTATE: glRotatef((GLfloat)this->rotate->x, (GLfloat)1.0f, (GLfloat)0.0f, (GLfloat)0.0f); glRotatef((GLfloat)this->rotate->y, (GLfloat)0.0f, (GLfloat)1.0f, (GLfloat)0.0f); glRotatef((GLfloat)this->rotate->z, (GLfloat)0.0f, (GLfloat)0.0f, (GLfloat)1.0f); break; case SCALE: glScalef((GLfloat)this->scale->x, (GLfloat)this->scale->y, (GLfloat)this->scale->z); break; } for (int i=0; i<this->children->size(); i++) { - this->children->at(i)->render(); + this->children->at(i)->render(renderType); } glPopMatrix(); } \ No newline at end of file diff --git a/TransformNode.h b/TransformNode.h index 8de1dcc..6735c54 100644 --- a/TransformNode.h +++ b/TransformNode.h @@ -1,40 +1,40 @@ /* * TransformNode * * Scene Graph node for handling transformations * * Copyright 2010 Leonard Teo. All rights reserved. * */ #ifndef TRANSFORMNODE_H #define TRANSFORMNODE_H #include "Node.h" #ifdef __APPLE__ #include <OpenGL/gl.h> #include <GLUT/GLUT.h> #else #include <GL/glut.h> #endif enum TransformType { TRANSLATE, SCALE, ROTATE }; class TransformNode : public Node { public: //Data members TransformType transformType; //Methods TransformNode(enum TransformType); ~TransformNode(); - void render(); + void render(RenderType renderType = ALL_OBJECTS); }; #endif diff --git a/Vector3.cpp b/Vector3.cpp index 2852734..5b3cb42 100644 --- a/Vector3.cpp +++ b/Vector3.cpp @@ -1,26 +1,25 @@ #include "Vector3.h" Vector3::Vector3(void) { x = 0; y = 0; z = 0; } Vector3::Vector3(float nx, float ny, float nz) { x = nx; y = ny; z = nz; } Vector3::~Vector3(void) { - delete this; } //Overloaded << operator std::ostream& operator<<(std::ostream& output, const Vector3* v) { output << "(" << v->x << ", " << v->y <<", " << v->z << ")"; return output; // for multiple << operators. } diff --git a/models/LightCycle_Axel_Front_Left.obj b/models/LightCycle_Axel_Front_Left.obj deleted file mode 100644 index b19cae6..0000000 --- a/models/LightCycle_Axel_Front_Left.obj +++ /dev/null @@ -1,174 +0,0 @@ -# This file uses centimeters as units for non-parametric coordinates. - -mtllib LightCycle_Axel_Front_Left.mtl -g default -v -1.230288 -0.184869 -0.201985 -v -1.230288 -0.190575 0.000000 -v -0.754431 -0.184869 -0.201985 -v -0.754431 -0.179163 0.000000 -v -1.230288 -0.184869 0.201986 -v -0.754431 -0.184869 0.201986 -v -0.278573 -0.184869 -0.201985 -v -0.278573 -0.190575 0.000000 -v -0.278573 -0.184869 0.201986 -v -1.230288 -0.476113 0.000000 -v -1.230288 -0.476113 0.259918 -v -0.754431 -0.476113 0.259918 -v -0.278573 -0.476113 0.259918 -v -0.278573 -0.476113 0.000000 -v -0.278573 -0.476113 -0.259917 -v -0.754431 -0.476113 -0.259917 -v -1.230288 -0.476113 -0.259917 -v 0.108873 -0.476113 0.259918 -v 0.108873 -0.476113 0.000000 -v 0.108873 -0.184869 0.201986 -v 0.108873 -0.190575 0.000000 -v 0.108873 -0.476113 -0.259917 -v 0.108873 -0.184869 -0.201985 -v -1.230288 -0.830581 0.000000 -v -1.230288 -0.767357 -0.317849 -v -0.754431 -0.767357 -0.317849 -v -1.230288 -0.767357 0.317850 -v -0.754431 -0.767357 0.317850 -v -0.278573 -0.767357 -0.317849 -v -0.278573 -0.830581 0.000000 -v -0.278573 -0.767357 0.317850 -vt 0.500000 0.875000 -vt 0.437500 0.875000 -vt 0.437500 0.750000 -vt 0.500000 0.750000 -vt 0.562500 0.875000 -vt 0.562500 0.750000 -vt 0.437500 0.625000 -vt 0.500000 0.625000 -vt 0.562500 0.625000 -vt 0.500000 0.875000 -vt 0.437500 0.875000 -vt 0.437500 0.875000 -vt 0.500000 0.875000 -vt 0.437500 0.750000 -vt 0.437500 0.750000 -vt 0.562500 0.875000 -vt 0.562500 0.875000 -vt 0.562500 0.750000 -vt 0.562500 0.750000 -vt 0.437500 0.625000 -vt 0.437500 0.625000 -vt 0.500000 0.625000 -vt 0.500000 0.625000 -vt 0.562500 0.625000 -vt 0.562500 0.625000 -vt 0.500000 0.625000 -vt 0.562500 0.625000 -vt 0.562500 0.625000 -vt 0.500000 0.625000 -vt 0.437500 0.625000 -vt 0.437500 0.625000 -vn -0.011990 0.999928 0.000000 -vn -0.000000 1.000000 0.000000 -vn -0.000000 1.000000 0.000000 -vn -0.011990 0.999928 0.000000 -vn -0.011990 0.999928 0.000000 -vn -0.000000 1.000000 -0.000000 -vn 0.005996 0.999982 0.000000 -vn 0.005996 0.999882 0.014121 -vn 0.005996 0.999882 -0.014121 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn 0.000000 0.195090 -0.980785 -vn -0.000000 0.195090 -0.980785 -vn -0.000000 0.195090 -0.980785 -vn 0.000000 0.195090 -0.980785 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn 0.000000 0.195091 0.980785 -vn 0.000000 0.195090 0.980785 -vn 0.000000 0.195090 0.980785 -vn 0.000000 0.195091 0.980785 -vn 0.000000 0.195090 -0.980785 -vn 0.000000 0.195090 -0.980785 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000001 0.000000 -vn 1.000000 -0.000001 0.000000 -vn 0.000000 0.195091 0.980785 -vn 0.000000 0.195090 0.980785 -vn -1.000000 0.000001 0.000000 -vn -1.000000 0.000000 0.000000 -vn 0.000000 0.195090 0.980785 -vn 0.000000 0.195090 0.980785 -vn 0.000000 0.195090 0.980785 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn -0.000000 0.195091 -0.980785 -vn 0.000000 0.195091 -0.980785 -vn -0.000000 0.195091 -0.980785 -vn -1.000000 0.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 0.195090 0.980785 -vn 0.000000 0.195090 0.980785 -vn -0.000000 0.999601 -0.028239 -vn -0.000000 1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn -0.000000 0.999601 0.028239 -vn 0.000000 0.195090 -0.980785 -vn 0.000000 0.195090 -0.980785 -s 1 -g Axel_Front_Left -usemtl initialShadingGroup -f 2/1/1 4/4/2 3/3/3 1/2/4 -f 5/5/5 6/6/6 4/4/2 2/1/1 -f 4/4/2 8/8/7 7/7/8 3/3/3 -f 6/6/6 9/9/9 8/8/7 4/4/2 -s 2 -f 24/10/10 10/13/11 17/12/12 25/11/13 -s 3 -f 25/11/14 17/12/15 16/15/16 26/14/17 -s 2 -f 27/16/18 11/17/19 10/13/11 24/10/10 -s 4 -f 28/18/20 12/19/21 11/17/22 27/16/23 -s 3 -f 26/14/17 16/15/16 15/21/24 29/20/25 -s 5 -f 29/20/26 15/21/27 14/23/28 30/22/29 -f 30/22/29 14/23/28 13/25/30 31/24/31 -s 4 -f 31/24/32 13/25/33 12/19/21 28/18/20 -s 2 -f 11/17/19 5/5/34 2/1/35 10/13/11 -s 4 -f 12/19/21 6/6/36 5/5/37 11/17/22 -f 13/25/33 9/9/38 6/6/36 12/19/21 -s 6 -f 19/26/39 21/29/40 20/28/41 18/27/42 -f 22/30/43 23/31/44 21/29/40 19/26/39 -s 3 -f 16/15/16 3/3/45 7/7/46 15/21/24 -f 17/12/15 1/2/47 3/3/45 16/15/16 -s 2 -f 10/13/11 2/1/35 1/2/48 17/12/12 -s 7 -f 14/23/49 19/26/50 18/27/51 13/25/52 -s 4 -f 13/25/33 18/27/53 20/28/54 9/9/38 -s 1 -f 9/9/9 20/28/55 21/29/56 8/8/7 -s 7 -f 15/21/57 22/30/58 19/26/50 14/23/49 -s 1 -f 8/8/7 21/29/56 23/31/59 7/7/8 -s 3 -f 7/7/46 23/31/60 22/30/61 15/21/24 diff --git a/models/LightCycle_Axel_Front_Right.obj b/models/LightCycle_Axel_Front_Right.obj deleted file mode 100644 index 16cc9ae..0000000 --- a/models/LightCycle_Axel_Front_Right.obj +++ /dev/null @@ -1,174 +0,0 @@ -# This file uses centimeters as units for non-parametric coordinates. - -mtllib LightCycle_Axel_Front_Right.mtl -g default -v 1.230288 -0.184869 -0.201985 -v 1.230288 -0.190575 0.000000 -v 0.754431 -0.184869 -0.201985 -v 0.754431 -0.179163 0.000000 -v 1.230288 -0.184869 0.201986 -v 0.754431 -0.184869 0.201986 -v 0.278574 -0.184869 -0.201985 -v 0.278573 -0.190575 0.000000 -v 0.278574 -0.184869 0.201986 -v 1.230288 -0.476113 0.000000 -v 1.230288 -0.476113 0.259918 -v 0.754431 -0.476113 0.259918 -v 0.278573 -0.476113 0.259918 -v 0.278573 -0.476113 0.000000 -v 0.278573 -0.476113 -0.259917 -v 0.754431 -0.476113 -0.259917 -v 1.230288 -0.476113 -0.259917 -v -0.108873 -0.476113 0.259918 -v -0.108873 -0.476113 0.000000 -v -0.108873 -0.184869 0.201986 -v -0.108873 -0.190575 0.000000 -v -0.108873 -0.476113 -0.259917 -v -0.108873 -0.184869 -0.201985 -v 1.230288 -0.830581 0.000000 -v 1.230288 -0.767357 -0.317849 -v 0.754431 -0.767357 -0.317849 -v 1.230288 -0.767357 0.317850 -v 0.754431 -0.767357 0.317850 -v 0.278574 -0.767357 -0.317849 -v 0.278573 -0.830581 0.000000 -v 0.278573 -0.767357 0.317850 -vt 0.500000 0.875000 -vt 0.437500 0.875000 -vt 0.437500 0.750000 -vt 0.500000 0.750000 -vt 0.562500 0.875000 -vt 0.562500 0.750000 -vt 0.437500 0.625000 -vt 0.500000 0.625000 -vt 0.562500 0.625000 -vt 0.500000 0.875000 -vt 0.437500 0.875000 -vt 0.437500 0.875000 -vt 0.500000 0.875000 -vt 0.437500 0.750000 -vt 0.437500 0.750000 -vt 0.562500 0.875000 -vt 0.562500 0.875000 -vt 0.562500 0.750000 -vt 0.562500 0.750000 -vt 0.437500 0.625000 -vt 0.437500 0.625000 -vt 0.500000 0.625000 -vt 0.500000 0.625000 -vt 0.562500 0.625000 -vt 0.562500 0.625000 -vt 0.500000 0.625000 -vt 0.562500 0.625000 -vt 0.562500 0.625000 -vt 0.500000 0.625000 -vt 0.437500 0.625000 -vt 0.437500 0.625000 -vn 0.011990 0.999928 0.000000 -vn 0.011990 0.999928 0.000000 -vn 0.000000 1.000000 0.000000 -vn 0.000000 1.000000 0.000000 -vn 0.011990 0.999928 0.000000 -vn 0.000000 1.000000 -0.000000 -vn -0.005996 0.999882 0.014121 -vn -0.005996 0.999982 0.000000 -vn -0.005996 0.999882 -0.014121 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000001 0.000000 -vn 1.000000 0.000000 0.000000 -vn 0.000000 0.195090 -0.980785 -vn 0.000000 0.195090 -0.980785 -vn 0.000000 0.195090 -0.980785 -vn 0.000000 0.195090 -0.980785 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 0.000000 0.195091 0.980785 -vn 0.000000 0.195091 0.980785 -vn 0.000000 0.195090 0.980785 -vn 0.000000 0.195090 0.980785 -vn 0.000000 0.195090 -0.980785 -vn 0.000000 0.195090 -0.980785 -vn -1.000000 0.000000 -0.000000 -vn -1.000000 0.000000 -0.000000 -vn -1.000000 0.000000 -0.000000 -vn -1.000000 0.000000 -0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn 0.000000 0.195091 0.980785 -vn 0.000000 0.195090 0.980785 -vn 1.000000 0.000001 0.000000 -vn 1.000000 0.000001 0.000000 -vn 0.000000 0.195090 0.980785 -vn 0.000000 0.195090 0.980785 -vn 0.000000 0.195090 0.980785 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn 0.000000 0.195091 -0.980785 -vn 0.000000 0.195090 -0.980785 -vn 0.000000 0.195090 -0.980785 -vn 1.000000 0.000001 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 0.195090 0.980785 -vn 0.000000 0.195090 0.980785 -vn 0.000000 1.000000 0.000000 -vn 0.000000 0.999601 -0.028239 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 0.999601 0.028239 -vn 0.000000 0.195091 -0.980785 -vn 0.000000 0.195091 -0.980785 -s 1 -g Axel_Front_Right -usemtl initialShadingGroup -f 2/1/1 1/2/2 3/3/3 4/4/4 -f 5/5/5 2/1/1 4/4/4 6/6/6 -f 4/4/4 3/3/3 7/7/7 8/8/8 -f 6/6/6 4/4/4 8/8/8 9/9/9 -s 2 -f 24/10/10 25/11/11 17/12/12 10/13/13 -s 3 -f 25/11/14 26/14/15 16/15/16 17/12/17 -s 2 -f 27/16/18 24/10/10 10/13/13 11/17/19 -s 4 -f 28/18/20 27/16/21 11/17/22 12/19/23 -s 3 -f 26/14/15 29/20/24 15/21/25 16/15/16 -s 5 -f 29/20/26 30/22/27 14/23/28 15/21/29 -f 30/22/27 31/24/30 13/25/31 14/23/28 -s 4 -f 31/24/32 28/18/20 12/19/23 13/25/33 -s 2 -f 11/17/19 10/13/13 2/1/34 5/5/35 -s 4 -f 12/19/23 11/17/22 5/5/36 6/6/37 -f 13/25/33 12/19/23 6/6/37 9/9/38 -s 6 -f 19/26/39 18/27/40 20/28/41 21/29/42 -f 22/30/43 19/26/39 21/29/42 23/31/44 -s 3 -f 16/15/16 15/21/25 7/7/45 3/3/46 -f 17/12/17 16/15/16 3/3/46 1/2/47 -s 2 -f 10/13/13 17/12/12 1/2/48 2/1/34 -s 7 -f 14/23/49 13/25/50 18/27/51 19/26/52 -s 4 -f 13/25/33 9/9/38 20/28/53 18/27/54 -s 1 -f 9/9/9 8/8/8 21/29/55 20/28/56 -s 7 -f 15/21/57 14/23/49 19/26/52 22/30/58 -s 1 -f 8/8/8 7/7/7 23/31/59 21/29/55 -s 3 -f 7/7/45 15/21/25 22/30/60 23/31/61 diff --git a/models/LightCycle_Canopy.obj b/models/LightCycle_Canopy.obj deleted file mode 100644 index f3eaa94..0000000 --- a/models/LightCycle_Canopy.obj +++ /dev/null @@ -1,1453 +0,0 @@ -# This file uses centimeters as units for non-parametric coordinates. - -mtllib LightCycle_Canopy.mtl -g default -v 0.000000 0.038779 -0.210295 -v 0.000000 0.038779 -0.528142 -v 0.000000 0.088819 -0.898218 -v 0.000000 0.000000 0.000000 -v 0.458742 -0.190017 0.000000 -v 0.863139 -0.103736 -0.344333 -v 0.957641 -0.047178 -0.635372 -v 0.990580 -0.026479 -1.130550 -v 0.916232 0.010873 -1.581053 -v 0.000000 0.114869 -1.447015 -v 0.000000 0.052760 0.000000 -v 0.458742 -0.137257 0.000000 -v 0.863139 -0.050977 -0.344333 -v 0.000000 0.091538 -0.210295 -v 0.957641 0.075587 -0.635372 -v 0.000000 0.140719 -0.528142 -v 0.990580 0.117692 -1.130550 -v 0.000000 0.202064 -0.898218 -v 0.916232 0.130408 -1.581053 -v 0.000000 0.242592 -1.447015 -v 1.493382 -0.103736 -0.496098 -v 1.740302 -0.047178 -0.875312 -v 1.740302 0.005581 -0.875312 -v 1.493382 -0.050977 -0.496098 -v 1.830434 -0.047178 -1.310966 -v 1.830434 0.023792 -1.310966 -v 1.831683 -0.018357 -1.714767 -v 1.831683 0.065330 -1.714767 -v 1.458828 0.070742 -1.220758 -v 1.332280 0.112280 -1.730870 -v 1.332280 0.039695 -1.730870 -v 1.458828 -0.047178 -1.220758 -v 1.395686 -0.047178 -0.755342 -v 1.178261 -0.103736 -0.420215 -v 1.178261 -0.050977 -0.420215 -v 1.395686 0.040584 -0.755342 -v 1.374721 0.314142 -3.426796 -v 1.374721 0.261119 -3.415030 -v 1.831875 0.267192 -3.422862 -v 1.831875 0.214432 -3.413003 -v 1.831875 0.244550 -3.124911 -v 1.370555 0.291500 -3.066197 -v 1.370555 0.235442 -3.066197 -v 1.831875 0.188755 -3.124911 -v 0.000000 0.389824 -3.106230 -v 0.000000 0.333766 -3.106230 -v -0.000000 0.412466 -3.431004 -v 0.000000 0.359444 -3.412938 -v 1.583249 -0.103736 -0.533756 -v 1.806699 -0.047178 -0.875312 -v 1.806699 0.005581 -0.875312 -v 1.583249 -0.050977 -0.533756 -v 1.896831 -0.047178 -1.310966 -v 1.896831 0.023792 -1.310966 -v 1.896831 -0.018357 -1.714767 -v 1.896831 0.065330 -1.714767 -v 1.896831 0.188755 -3.124911 -v 1.896831 0.244550 -3.124911 -v 1.896831 0.214432 -3.413003 -v 1.896831 0.267192 -3.422862 -v 1.493382 -0.225343 -0.496098 -v 1.740302 -0.376939 -1.062548 -v 1.806699 -0.376939 -1.062548 -v 1.583249 -0.225343 -0.533756 -v 1.830434 -0.376939 -1.415184 -v 1.896831 -0.376939 -1.415184 -v 1.831683 -0.348118 -1.923735 -v 1.896831 -0.348118 -1.923735 -v 1.831875 -0.141006 -3.124911 -v 1.896831 -0.141006 -3.124911 -v 1.831875 -0.115328 -3.349149 -v 1.896831 -0.115328 -3.349149 -v 1.801410 -0.895884 -1.467383 -v 1.830434 -0.895884 -1.635318 -v 1.896831 -0.895884 -1.635318 -v 1.867807 -0.895884 -1.467383 -v 1.831683 -0.895884 -2.280955 -v 1.896831 -0.895884 -2.280955 -v 1.831875 -0.895884 -2.756998 -v 1.896831 -0.895884 -2.756998 -v 0.919521 0.358359 -3.079125 -v 0.919521 0.302301 -3.079125 -v 0.930773 0.327978 -3.414354 -v 0.930773 0.381001 -3.428155 -v 0.000000 0.240255 -1.167656 -v 0.000000 0.104203 -1.167656 -v 0.929892 0.000207 -1.378121 -v 1.355531 0.023734 -1.637148 -v 1.831454 -0.023652 -1.640577 -v 1.831454 -0.353413 -1.830300 -v 1.831454 -0.895884 -2.162333 -v 1.896831 -0.895884 -2.162333 -v 1.896831 -0.353413 -1.830300 -v 1.896831 -0.023652 -1.640577 -v 1.896831 0.057698 -1.640577 -v 1.831454 0.057698 -1.640577 -v 1.355531 0.104648 -1.637148 -v 0.929892 0.128072 -1.378121 -v 1.428572 0.285596 -3.073581 -v 1.395086 0.106375 -1.728845 -v 1.380063 0.098744 -1.678909 -v 1.505562 0.064837 -1.232103 -v 1.439026 0.036182 -0.770430 -v 1.217891 -0.050977 -0.429759 -v 1.217891 -0.103736 -0.429759 -v 1.439026 -0.047178 -0.770430 -v 1.505562 -0.047178 -1.232103 -v 1.415384 0.017775 -1.637579 -v 1.395086 0.032394 -1.728845 -v 1.428572 0.229571 -3.073581 -v 1.432214 0.255248 -3.414775 -v 1.432214 0.308237 -3.426301 -v 0.814908 0.507158 -1.814834 -v 0.803414 0.509494 -1.897605 -v 1.231393 0.483287 -1.983937 -v 1.212523 0.488931 -2.059242 -v 0.000000 0.510976 -1.675085 -v 0.000000 0.513313 -1.757856 -v 1.271142 0.482444 -2.052142 -v 1.318664 0.566512 -2.969277 -v 1.266932 0.572416 -2.961893 -v 1.256863 0.476801 -2.010555 -v -0.458742 -0.190017 0.000000 -v -0.863139 -0.103736 -0.344333 -v -0.957641 -0.047178 -0.635372 -v -0.990580 -0.026479 -1.130550 -v -1.005620 0.010873 -1.581053 -v -0.458742 -0.137257 0.000000 -v -0.863139 -0.050977 -0.344333 -v -0.957641 0.075587 -0.635372 -v -0.990580 0.117692 -1.130550 -v -1.005620 0.130408 -1.581053 -v -1.493382 -0.103736 -0.496098 -v -1.740302 -0.047178 -0.875312 -v -1.740302 0.005581 -0.875312 -v -1.493382 -0.050977 -0.496098 -v -1.830434 -0.047178 -1.310966 -v -1.830434 0.023792 -1.310966 -v -1.831683 -0.018357 -1.714767 -v -1.831683 0.065330 -1.714767 -v -1.458828 0.070742 -1.220758 -v -1.332280 0.112280 -1.730870 -v -1.332280 0.039695 -1.730870 -v -1.458828 -0.047178 -1.220758 -v -1.395686 -0.047178 -0.755342 -v -1.178261 -0.103736 -0.420215 -v -1.178261 -0.050977 -0.420215 -v -1.395686 0.040584 -0.755342 -v -1.374721 0.314142 -3.426796 -v -1.374721 0.261119 -3.415030 -v -1.831875 0.267192 -3.422862 -v -1.831875 0.214432 -3.413003 -v -1.831875 0.244550 -3.124911 -v -1.370555 0.291500 -3.066197 -v -1.370555 0.235442 -3.066197 -v -1.831875 0.188755 -3.124911 -v -1.583249 -0.103736 -0.533756 -v -1.806699 -0.047178 -0.875312 -v -1.806699 0.005581 -0.875312 -v -1.583249 -0.050977 -0.533756 -v -1.896831 -0.047178 -1.310966 -v -1.896831 0.023792 -1.310966 -v -1.896831 -0.018357 -1.714767 -v -1.896831 0.065330 -1.714767 -v -1.896831 0.188755 -3.124911 -v -1.896831 0.244550 -3.124911 -v -1.896831 0.214432 -3.413003 -v -1.896831 0.267192 -3.422862 -v -1.493382 -0.225343 -0.496098 -v -1.740302 -0.376939 -1.062548 -v -1.806699 -0.376939 -1.062548 -v -1.583249 -0.225343 -0.533756 -v -1.830434 -0.376939 -1.415184 -v -1.896831 -0.376939 -1.415184 -v -1.831683 -0.348118 -1.923735 -v -1.896831 -0.348118 -1.923735 -v -1.831875 -0.141006 -3.124911 -v -1.896831 -0.141006 -3.124911 -v -1.831875 -0.115328 -3.349149 -v -1.896831 -0.115328 -3.349149 -v -1.801410 -0.895884 -1.467383 -v -1.830434 -0.895884 -1.635318 -v -1.896831 -0.895884 -1.635318 -v -1.867807 -0.895884 -1.467383 -v -1.831683 -0.895884 -2.280955 -v -1.896831 -0.895884 -2.280955 -v -1.831875 -0.895884 -2.756998 -v -1.896831 -0.895884 -2.756998 -v -0.919521 0.358359 -3.079125 -v -0.919521 0.302301 -3.079125 -v -0.930773 0.327978 -3.414354 -v -0.930773 0.381001 -3.428155 -v -0.929892 0.000207 -1.378121 -v -1.355531 0.023734 -1.637148 -v -1.831454 -0.023652 -1.640577 -v -1.831454 -0.353413 -1.830300 -v -1.831454 -0.895884 -2.162333 -v -1.896831 -0.895884 -2.162333 -v -1.896831 -0.353413 -1.830300 -v -1.896831 -0.023652 -1.640577 -v -1.896831 0.057698 -1.640577 -v -1.831454 0.057698 -1.640577 -v -1.355531 0.104648 -1.637148 -v -0.929892 0.128072 -1.378121 -v -1.428572 0.285596 -3.073581 -v -1.395086 0.106375 -1.728845 -v -1.380063 0.098744 -1.678909 -v -1.505562 0.064837 -1.232103 -v -1.439026 0.036182 -0.770430 -v -1.217891 -0.050977 -0.429759 -v -1.217891 -0.103736 -0.429759 -v -1.439026 -0.047178 -0.770430 -v -1.505562 -0.047178 -1.232103 -v -1.415384 0.017775 -1.637579 -v -1.395086 0.032394 -1.728845 -v -1.428572 0.229571 -3.073581 -v -1.432214 0.255248 -3.414775 -v -1.432214 0.308237 -3.426301 -v -0.814908 0.507158 -1.814834 -v -0.803414 0.509494 -1.897605 -v -1.231393 0.483287 -1.983937 -v -1.212523 0.488931 -2.059242 -v -1.271142 0.482444 -2.052142 -v -1.318664 0.566512 -2.969277 -v -1.266932 0.572416 -2.961893 -v -1.256863 0.476801 -2.010555 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.500000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.000000 0.000000 -vt 1.000000 0.000000 -vt 1.000000 1.000000 -vt 0.000000 1.000000 -vn -0.000000 0.914792 0.403926 -vn 0.261639 0.882926 0.389856 -vn 0.184435 0.914982 0.358876 -vn -0.000000 0.936329 0.351125 -vn 0.125196 0.966360 0.224664 -vn -0.000000 0.977481 0.211026 -vn 0.105281 0.991031 0.082299 -vn 0.000000 0.994887 0.100997 -vn 0.107296 0.992359 0.060921 -vn 0.000000 0.996833 0.079521 -vn -0.261639 -0.882925 -0.389856 -vn -0.261639 -0.882925 -0.389856 -vn -0.261639 -0.882925 -0.389856 -vn -0.261639 -0.882925 -0.389856 -vn -0.138420 -0.983920 -0.112877 -vn -0.127774 -0.986837 -0.099129 -vn -0.084451 -0.990697 -0.106714 -vn -0.095779 -0.982750 -0.158205 -vn -0.122601 -0.989586 -0.075425 -vn -0.080800 -0.993729 -0.077287 -vn -0.123722 -0.990901 -0.052999 -vn -0.069901 -0.994101 -0.082926 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.648297 0.000000 0.761388 -vn 0.648297 0.000000 0.761388 -vn 0.648297 0.000000 0.761388 -vn 0.648297 0.000000 0.761388 -vn 0.836830 0.000000 0.547463 -vn 0.836830 0.000000 0.547463 -vn 0.836830 0.000000 0.547463 -vn 0.836830 0.000000 0.547463 -vn 0.979262 0.000000 0.202599 -vn 0.994802 0.000000 0.101829 -vn 0.994802 0.000000 0.101829 -vn 0.979262 0.000000 0.202599 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn -0.242994 0.000000 -0.970028 -vn -0.144752 0.000000 -0.989468 -vn -0.163668 -0.378248 -0.911121 -vn -0.251474 -0.370505 -0.894140 -vn -0.035525 -0.993514 -0.108016 -vn -0.056462 -0.977596 -0.202779 -vn 0.147239 0.918915 0.365946 -vn 0.136668 0.964210 0.227201 -vn 0.234113 0.000000 0.972210 -vn 0.234113 0.000000 0.972210 -vn 0.234112 0.000000 0.972210 -vn 0.234112 0.000000 0.972210 -vn -0.037290 -0.996394 -0.076212 -vn 0.131455 0.989524 0.059679 -vn -0.051947 -0.990476 -0.127513 -vn -0.336570 -0.359875 -0.870179 -vn -0.338799 0.000000 -0.940859 -vn 0.139658 0.989557 0.035678 -vn 0.125565 0.989124 0.076595 -vn 0.141219 0.987928 0.063692 -vn 0.121810 0.989923 0.072213 -vn 0.096067 0.990285 0.100531 -vn -0.014760 -0.206395 -0.978357 -vn -0.014760 -0.206395 -0.978357 -vn -0.013908 -0.198199 -0.980063 -vn -0.013908 -0.198199 -0.980063 -vn -0.034857 -0.997306 -0.064540 -vn -0.087332 -0.988243 -0.125495 -vn -0.086626 -0.990294 -0.108691 -vn -0.033929 -0.997872 -0.055683 -vn -0.029358 -0.994665 -0.098891 -vn -0.028466 -0.994985 -0.095889 -vn -0.058402 -0.978717 -0.196730 -vn -0.056647 -0.979990 -0.190816 -vn 0.234112 0.000000 0.972210 -vn 0.234112 0.000000 0.972210 -vn 0.234113 0.000000 0.972210 -vn 0.234113 0.000000 0.972210 -vn 0.139936 0.970664 0.195525 -vn 0.141878 0.940123 0.309902 -vn 0.132495 0.951928 0.276187 -vn 0.134506 0.975047 0.176612 -vn -0.999590 0.000000 -0.028652 -vn -0.983018 -0.175137 -0.054794 -vn -0.983018 -0.175137 -0.054794 -vn -0.999590 0.000000 -0.028652 -vn 0.092847 0.987071 0.130657 -vn 0.092847 0.987071 0.130657 -vn 0.103903 0.989583 0.099646 -vn 0.104377 0.990653 0.087823 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn -0.109578 -0.985967 -0.125941 -vn -0.109373 -0.984887 -0.134294 -vn -0.109683 -0.987595 -0.112366 -vn -0.109750 -0.987445 -0.113613 -vn 0.105424 0.992175 0.066888 -vn 0.105566 0.991972 0.069626 -vn -0.105609 -0.991325 -0.078241 -vn -0.105781 -0.991045 -0.081489 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn -0.028651 0.000000 0.999590 -vn -0.028651 0.000000 0.999590 -vn -0.029058 0.000000 0.999578 -vn -0.029058 0.000000 0.999578 -vn 0.125873 0.989903 0.065171 -vn 0.125873 0.989903 0.065171 -vn 0.089762 0.993709 0.066973 -vn 0.089762 0.993709 0.066973 -vn -0.025072 -0.224430 -0.974167 -vn -0.025072 -0.224430 -0.974167 -vn -0.021771 -0.261128 -0.965059 -vn -0.021771 -0.261128 -0.965059 -vn -0.125890 -0.989115 -0.076179 -vn -0.121879 -0.987507 -0.099880 -vn -0.089675 -0.992839 -0.078932 -vn -0.089675 -0.992839 -0.078932 -vn 0.070923 -0.953079 0.294296 -vn 0.070923 -0.953079 0.294296 -vn 0.070923 -0.953079 0.294296 -vn 0.070923 -0.953079 0.294296 -vn 0.044077 0.982143 0.182899 -vn 0.044077 0.982143 0.182899 -vn 0.044077 0.982143 0.182899 -vn 0.044077 0.982143 0.182899 -vn 0.386483 0.000000 0.922297 -vn 0.386483 0.000000 0.922297 -vn 0.386483 0.000000 0.922297 -vn 0.386483 0.000000 0.922297 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 0.997399 0.072079 -vn 0.000000 0.999128 0.041765 -vn 0.000000 0.999128 0.041765 -vn 0.000000 0.997399 0.072079 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 0.994751 0.102327 -vn 0.000000 0.994751 0.102327 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 0.994891 0.100958 -vn 0.000000 0.993457 0.114211 -vn 0.000000 0.993457 0.114211 -vn 0.000000 0.994891 0.100958 -vn 0.000000 -0.993508 -0.113765 -vn 0.000000 -0.993508 -0.113765 -vn 0.000000 -0.993508 -0.113765 -vn 0.000000 -0.993508 -0.113765 -vn 0.000000 -0.183689 -0.982984 -vn 0.000000 -0.183689 -0.982984 -vn 0.000000 -0.183689 -0.982984 -vn 0.000000 -0.183689 -0.982984 -vn 0.000000 0.997125 0.075772 -vn 0.000000 0.997125 0.075772 -vn -0.861285 0.194693 -0.469343 -vn -0.861285 0.194693 -0.469343 -vn -0.861285 0.194693 -0.469343 -vn -0.861285 0.194693 -0.469343 -vn 0.864178 -0.192801 0.464785 -vn 0.864178 -0.192801 0.464785 -vn 0.864178 -0.192801 0.464785 -vn 0.864178 -0.192801 0.464785 -vn 0.386483 0.000000 0.922297 -vn 0.386483 0.000000 0.922297 -vn 0.386483 0.000000 0.922297 -vn 0.386483 0.000000 0.922297 -vn -0.970140 0.098039 -0.221849 -vn -0.992328 0.049979 -0.113084 -vn -0.992328 0.049979 -0.113084 -vn -0.970140 0.098039 -0.221849 -vn 0.992507 -0.049390 0.111762 -vn 0.970140 -0.098039 0.221849 -vn 0.970140 -0.098039 0.221849 -vn 0.992507 -0.049390 0.111762 -vn -0.999996 0.001391 -0.002650 -vn -0.999996 0.001391 -0.002650 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn -0.999999 0.000819 -0.001389 -vn -1.000000 0.000044 -0.000140 -vn -1.000000 0.000044 -0.000140 -vn -0.999999 0.000819 -0.001389 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn 0.000000 -0.190108 -0.981763 -vn 0.000000 -0.190108 -0.981763 -vn 0.000000 -0.190108 -0.981763 -vn 0.000000 -0.190108 -0.981763 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn -0.971916 0.076736 -0.222467 -vn -0.992812 0.039195 -0.113083 -vn -0.992812 0.039195 -0.113083 -vn -0.971916 0.076736 -0.222467 -vn 0.992954 -0.038640 0.112023 -vn 0.971916 -0.076736 0.222467 -vn 0.971916 -0.076736 0.222467 -vn 0.992954 -0.038640 0.112023 -vn 0.000000 -0.615087 0.788460 -vn 0.000000 -0.615087 0.788460 -vn 0.000000 -0.615087 0.788460 -vn 0.000000 -0.615087 0.788460 -vn -0.999997 0.001229 -0.002134 -vn -0.999997 0.001229 -0.002134 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn -0.999999 0.000673 -0.001180 -vn -1.000000 -0.000002 -0.000229 -vn -1.000000 -0.000002 -0.000229 -vn -0.999999 0.000673 -0.001180 -vn 0.000000 -0.438116 -0.898918 -vn 0.000000 -0.438116 -0.898918 -vn 0.000000 -0.438116 -0.898918 -vn 0.000000 -0.438116 -0.898918 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn -0.029465 0.000000 0.999566 -vn -0.029465 0.000000 0.999566 -vn -0.032769 -0.996234 -0.080272 -vn -0.032769 -0.996234 -0.080272 -vn -0.008991 -0.287772 -0.957657 -vn -0.008991 -0.287772 -0.957657 -vn 1.000000 0.000000 -0.000000 -vn 1.000000 0.000000 -0.000000 -vn 1.000000 0.000000 -0.000000 -vn 1.000000 0.000000 -0.000000 -vn -0.119323 -0.992029 -0.040497 -vn -0.051068 -0.996499 -0.066194 -vn -0.067094 -0.989776 -0.125866 -vn 0.039027 0.998714 0.032374 -vn 0.039027 0.998714 0.032374 -vn 0.120374 0.990748 0.062684 -vn 0.117364 0.990310 0.074244 -vn 0.009477 0.999575 0.027558 -vn 0.009477 0.999575 0.027558 -vn 0.141618 0.985573 0.092689 -vn 0.111303 0.989012 0.097295 -vn 0.111303 0.989012 0.097295 -vn 0.171799 0.981194 0.087994 -vn 0.255465 0.777838 0.574200 -vn 0.533529 0.673293 0.511882 -vn 0.533529 0.673293 0.511882 -vn 0.255465 0.777838 0.574200 -vn -0.224097 -0.687195 -0.691046 -vn -0.289069 -0.671342 -0.682450 -vn 0.000000 0.833103 0.553118 -vn 0.000000 0.833103 0.553118 -vn -0.158105 -0.699923 -0.696499 -vn 0.867199 0.454299 0.203907 -vn 0.931313 0.356447 0.074846 -vn 0.931313 0.356447 0.074846 -vn 0.867199 0.454299 0.203907 -vn -0.093161 0.315254 -0.944423 -vn -0.093161 0.315254 -0.944423 -vn -0.093161 0.315254 -0.944423 -vn -0.093161 0.315254 -0.944423 -vn -0.935353 -0.344734 -0.079204 -vn -0.935353 -0.344734 -0.079204 -vn 0.739093 0.565482 0.366020 -vn 0.739093 0.565482 0.366020 -vn -0.184435 0.914982 0.358876 -vn -0.261639 0.882926 0.389856 -vn -0.125196 0.966360 0.224664 -vn -0.105281 0.991031 0.082299 -vn -0.107296 0.992359 0.060921 -vn 0.261639 -0.882925 -0.389856 -vn 0.261639 -0.882925 -0.389856 -vn 0.261639 -0.882925 -0.389856 -vn 0.261639 -0.882925 -0.389856 -vn 0.138420 -0.983920 -0.112877 -vn 0.095779 -0.982750 -0.158204 -vn 0.084451 -0.990697 -0.106714 -vn 0.127774 -0.986837 -0.099129 -vn 0.080800 -0.993729 -0.077287 -vn 0.122601 -0.989586 -0.075425 -vn 0.068092 -0.993893 -0.086831 -vn 0.122848 -0.990366 -0.063896 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn -0.648297 0.000000 0.761387 -vn -0.648297 0.000000 0.761387 -vn -0.648297 0.000000 0.761387 -vn -0.648297 0.000000 0.761387 -vn -0.836830 0.000000 0.547463 -vn -0.836830 0.000000 0.547463 -vn -0.836830 0.000000 0.547463 -vn -0.836830 0.000000 0.547463 -vn -0.979262 0.000000 0.202599 -vn -0.979262 0.000000 0.202599 -vn -0.994802 0.000000 0.101829 -vn -0.994802 0.000000 0.101829 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn 0.277565 0.000000 -0.960707 -vn 0.275366 -0.381410 -0.882440 -vn 0.152738 -0.385153 -0.910126 -vn 0.132120 0.000000 -0.991234 -vn 0.056462 -0.977596 -0.202778 -vn 0.035525 -0.993514 -0.108016 -vn -0.136668 0.964210 0.227201 -vn -0.147239 0.918915 0.365946 -vn -0.234113 0.000000 0.972210 -vn -0.234112 0.000000 0.972210 -vn -0.234112 0.000000 0.972210 -vn -0.234113 0.000000 0.972210 -vn 0.037290 -0.996394 -0.076212 -vn -0.131455 0.989524 0.059679 -vn 0.050586 -0.990742 -0.125985 -vn 0.416880 0.000000 -0.908962 -vn 0.392888 -0.371716 -0.841110 -vn -0.139659 0.989557 0.035677 -vn -0.125565 0.989124 0.076595 -vn -0.096067 0.990285 0.100531 -vn -0.121810 0.989923 0.072213 -vn -0.141219 0.987927 0.063691 -vn 0.014760 -0.206395 -0.978357 -vn 0.013908 -0.198199 -0.980063 -vn 0.013908 -0.198199 -0.980063 -vn 0.014760 -0.206395 -0.978357 -vn 0.034857 -0.997306 -0.064540 -vn 0.033929 -0.997872 -0.055683 -vn 0.086626 -0.990294 -0.108691 -vn 0.087332 -0.988243 -0.125495 -vn 0.029358 -0.994665 -0.098891 -vn 0.028466 -0.994985 -0.095889 -vn 0.058402 -0.978717 -0.196730 -vn 0.056647 -0.979990 -0.190817 -vn -0.234112 0.000000 0.972210 -vn -0.234113 0.000000 0.972210 -vn -0.234113 0.000000 0.972210 -vn -0.234112 0.000000 0.972210 -vn -0.139936 0.970664 0.195525 -vn -0.134507 0.975047 0.176612 -vn -0.132495 0.951928 0.276187 -vn -0.141878 0.940123 0.309902 -vn 0.999590 0.000000 -0.028652 -vn 0.999590 0.000000 -0.028652 -vn 0.983018 -0.175137 -0.054794 -vn 0.983018 -0.175137 -0.054794 -vn -0.092847 0.987071 0.130657 -vn -0.104377 0.990653 0.087823 -vn -0.103903 0.989583 0.099647 -vn -0.092847 0.987071 0.130657 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn 0.109578 -0.985967 -0.125941 -vn 0.109750 -0.987445 -0.113613 -vn 0.109683 -0.987595 -0.112366 -vn 0.109373 -0.984887 -0.134294 -vn -0.105424 0.992175 0.066888 -vn -0.105566 0.991972 0.069626 -vn 1.000000 0.000000 -0.000000 -vn 1.000000 0.000000 -0.000000 -vn 1.000000 0.000000 -0.000000 -vn 1.000000 0.000000 -0.000000 -vn 0.105781 -0.991045 -0.081489 -vn 0.105609 -0.991325 -0.078241 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn 0.028652 0.000000 0.999590 -vn 0.029058 0.000000 0.999578 -vn 0.029058 0.000000 0.999578 -vn 0.028652 0.000000 0.999590 -vn -0.125873 0.989903 0.065171 -vn -0.089762 0.993709 0.066974 -vn -0.089762 0.993709 0.066974 -vn -0.125873 0.989903 0.065171 -vn 0.025072 -0.224431 -0.974167 -vn 0.021771 -0.261128 -0.965059 -vn 0.021771 -0.261128 -0.965059 -vn 0.025072 -0.224431 -0.974167 -vn 0.125890 -0.989115 -0.076180 -vn 0.089675 -0.992839 -0.078932 -vn 0.089675 -0.992839 -0.078932 -vn 0.121879 -0.987507 -0.099880 -vn -0.070923 -0.953079 0.294296 -vn -0.070923 -0.953079 0.294296 -vn -0.070923 -0.953079 0.294296 -vn -0.070923 -0.953079 0.294296 -vn -0.044077 0.982143 0.182899 -vn -0.044077 0.982143 0.182899 -vn -0.044077 0.982143 0.182899 -vn -0.044077 0.982143 0.182899 -vn -0.386483 0.000000 0.922297 -vn -0.386483 0.000000 0.922297 -vn -0.386483 0.000000 0.922297 -vn -0.386483 0.000000 0.922297 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 0.997399 0.072079 -vn 0.000000 0.997399 0.072079 -vn 0.000000 0.999128 0.041765 -vn 0.000000 0.999128 0.041765 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 0.994751 0.102327 -vn 0.000000 0.994751 0.102327 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 0.994891 0.100958 -vn 0.000000 0.994891 0.100958 -vn 0.000000 0.993457 0.114211 -vn 0.000000 0.993457 0.114211 -vn 0.000000 -0.993508 -0.113765 -vn 0.000000 -0.993508 -0.113765 -vn 0.000000 -0.993508 -0.113765 -vn 0.000000 -0.993508 -0.113765 -vn 0.000000 -0.183689 -0.982984 -vn 0.000000 -0.183689 -0.982984 -vn 0.000000 -0.183689 -0.982984 -vn 0.000000 -0.183689 -0.982984 -vn 0.000000 0.997125 0.075772 -vn 0.000000 0.997125 0.075772 -vn 0.861285 0.194693 -0.469343 -vn 0.861285 0.194693 -0.469343 -vn 0.861285 0.194693 -0.469343 -vn 0.861285 0.194693 -0.469343 -vn -0.864178 -0.192801 0.464785 -vn -0.864178 -0.192801 0.464785 -vn -0.864178 -0.192801 0.464785 -vn -0.864178 -0.192801 0.464785 -vn -0.386483 0.000000 0.922297 -vn -0.386483 0.000000 0.922297 -vn -0.386483 0.000000 0.922297 -vn -0.386483 0.000000 0.922297 -vn 0.970140 0.098039 -0.221849 -vn 0.970140 0.098039 -0.221849 -vn 0.992328 0.049979 -0.113084 -vn 0.992328 0.049979 -0.113084 -vn -0.992507 -0.049390 0.111762 -vn -0.992507 -0.049390 0.111762 -vn -0.970140 -0.098039 0.221849 -vn -0.970140 -0.098039 0.221849 -vn 0.999996 0.001391 -0.002650 -vn 0.999996 0.001391 -0.002650 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn 0.999999 0.000819 -0.001389 -vn 0.999999 0.000819 -0.001389 -vn 1.000000 0.000044 -0.000140 -vn 1.000000 0.000044 -0.000140 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 0.000000 -0.190108 -0.981763 -vn 0.000000 -0.190108 -0.981763 -vn 0.000000 -0.190108 -0.981763 -vn 0.000000 -0.190108 -0.981763 -vn -1.000000 -0.000001 0.000000 -vn -1.000000 -0.000001 0.000000 -vn 0.971916 0.076736 -0.222467 -vn 0.971916 0.076736 -0.222467 -vn 0.992812 0.039194 -0.113083 -vn 0.992812 0.039194 -0.113083 -vn -0.992954 -0.038640 0.112023 -vn -0.992954 -0.038640 0.112023 -vn -0.971916 -0.076736 0.222467 -vn -0.971916 -0.076736 0.222467 -vn 0.000000 -0.615087 0.788460 -vn 0.000000 -0.615087 0.788460 -vn 0.000000 -0.615087 0.788460 -vn 0.000000 -0.615087 0.788460 -vn 0.999997 0.001229 -0.002134 -vn 0.999997 0.001229 -0.002134 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn 0.999999 0.000673 -0.001180 -vn 0.999999 0.000673 -0.001180 -vn 1.000000 -0.000002 -0.000229 -vn 1.000000 -0.000002 -0.000229 -vn 0.000000 -0.438116 -0.898918 -vn 0.000000 -0.438116 -0.898918 -vn 0.000000 -0.438116 -0.898918 -vn 0.000000 -0.438116 -0.898918 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn 0.029465 0.000000 0.999566 -vn 0.029465 0.000000 0.999566 -vn 0.032769 -0.996234 -0.080272 -vn 0.032769 -0.996234 -0.080272 -vn 0.008991 -0.287772 -0.957657 -vn 0.008991 -0.287772 -0.957657 -vn -0.032821 0.997175 0.067565 -vn -0.032821 0.997175 0.067565 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn 0.047454 -0.996128 -0.074013 -vn 0.117594 -0.991106 -0.062300 -vn 0.065283 -0.990154 -0.123829 -vn -0.039027 0.998714 0.032375 -vn -0.117364 0.990310 0.074245 -vn -0.120374 0.990748 0.062685 -vn -0.039027 0.998714 0.032375 -vn -0.009477 0.999575 0.027558 -vn -0.009477 0.999575 0.027558 -vn -0.111303 0.989012 0.097296 -vn -0.111303 0.989012 0.097296 -vn -0.141619 0.985572 0.092690 -vn -0.171799 0.981194 0.087995 -vn -0.255465 0.777838 0.574200 -vn -0.255465 0.777838 0.574200 -vn -0.533530 0.673293 0.511882 -vn -0.533530 0.673293 0.511882 -vn 0.312576 -0.690146 -0.652683 -vn 0.231920 -0.702790 -0.672532 -vn 0.149628 -0.710474 -0.687633 -vn -0.867199 0.454299 0.203906 -vn -0.867199 0.454299 0.203906 -vn -0.931313 0.356447 0.074846 -vn -0.931313 0.356447 0.074846 -vn 0.093163 0.315254 -0.944423 -vn 0.093163 0.315254 -0.944423 -vn 0.093163 0.315254 -0.944423 -vn 0.093163 0.315254 -0.944423 -vn 0.935353 -0.344734 -0.079204 -vn 0.935353 -0.344734 -0.079204 -vn -0.739094 0.565482 0.366020 -vn -0.739094 0.565482 0.366020 -vn 0.032822 0.997175 0.067564 -vn 0.032822 0.997175 0.067564 -s 1 -g Canopy -usemtl initialShadingGroup -f 11/21/1 12/22/2 13/23/3 14/4/4 -f 14/4/4 13/23/3 15/24/5 16/6/6 -f 16/6/6 15/24/5 17/25/7 18/8/8 -f 18/8/8 17/25/7 98/110/9 85/96/10 -s off -f 4/11/11 1/14/12 6/13/13 5/12/14 -s 2 -f 1/14/15 2/16/16 7/15/17 6/13/18 -f 2/16/16 3/18/19 8/17/20 7/15/17 -f 3/18/19 86/97/21 87/99/22 8/17/20 -s off -f 4/1/23 5/2/24 12/22/25 11/21/26 -f 5/2/27 6/3/28 13/23/29 12/22/30 -f 49/56/31 50/57/32 51/58/33 52/59/34 -s 3 -f 50/57/35 53/60/36 54/61/37 51/58/38 -f 53/60/36 94/106/39 95/107/40 54/61/37 -s 4 -f 9/9/41 10/10/42 20/27/43 19/26/44 -s 2 -f 6/3/18 7/5/17 33/40/45 34/41/46 -s 1 -f 15/24/5 13/23/3 35/42/47 36/43/48 -s 5 -f 13/23/49 6/3/50 34/41/51 35/42/52 -s 2 -f 7/5/17 8/7/20 32/39/53 33/40/45 -s 1 -f 17/25/7 15/24/5 36/43/48 29/36/54 -s 2 -f 8/7/20 87/98/22 88/100/55 32/39/53 -s 4 -f 9/9/41 19/26/44 30/37/56 31/38/57 -s 1 -f 98/110/9 17/25/7 29/36/54 97/109/58 -f 101/113/59 102/114/60 26/33/61 96/108/62 -s 6 -f 111/123/63 112/124/64 39/46/65 40/47/66 -s 2 -f 107/119/67 108/120/68 89/101/69 25/32/70 -f 106/118/71 107/119/67 25/32/70 22/29/72 -f 105/117/73 106/118/71 22/29/72 21/28/74 -s 5 -f 104/116/75 105/117/76 21/28/77 24/31/78 -s 1 -f 103/115/79 104/116/80 24/31/81 23/30/82 -f 102/114/60 103/115/79 23/30/82 26/33/61 -s 7 -f 31/38/83 30/37/84 42/49/85 43/50/86 -s 1 -f 100/112/87 28/35/88 41/48/89 99/111/90 -s 3 -f 56/63/91 55/62/92 57/64/93 58/65/94 -s 2 -f 27/34/95 109/121/96 110/122/97 44/51/98 -s 1 -f 112/124/99 99/111/90 41/48/89 39/46/100 -s 2 -f 44/51/98 110/122/97 111/123/101 40/47/102 -s 3 -f 58/65/94 57/64/93 59/66/103 60/67/104 -s 8 -f 43/50/105 42/49/106 81/88/107 82/89/108 -s 1 -f 42/49/109 37/45/110 84/91/111 81/88/112 -s 6 -f 37/45/113 38/44/114 83/90/115 84/91/116 -s 2 -f 38/44/117 43/50/118 82/89/119 83/90/120 -s off -f 61/68/121 62/69/122 63/70/123 64/71/124 -f 23/30/125 24/31/126 52/59/127 51/58/128 -f 24/31/129 21/28/130 49/56/131 52/59/132 -s 9 -f 73/80/133 74/81/134 75/82/135 76/83/136 -s 10 -f 26/33/137 23/30/138 51/58/139 54/61/140 -s 9 -f 74/81/134 91/103/141 92/104/142 75/82/135 -s 10 -f 96/108/143 26/33/137 54/61/140 95/107/144 -s 9 -f 77/84/145 79/86/146 80/87/147 78/85/148 -s 10 -f 41/48/149 28/35/150 56/63/151 58/65/152 -s off -f 69/76/153 71/78/154 72/79/155 70/77/156 -f 40/47/157 39/46/158 60/67/159 59/66/160 -s 10 -f 39/46/161 41/48/149 58/65/152 60/67/162 -s off -f 21/28/163 22/29/164 62/69/165 61/68/166 -f 50/57/167 49/56/168 64/71/169 63/70/170 -f 49/56/171 21/28/172 61/68/173 64/71/174 -s 11 -f 22/29/175 25/32/176 65/72/177 62/69/178 -s 12 -f 53/60/179 50/57/180 63/70/181 66/73/182 -s 11 -f 25/32/176 89/101/183 90/102/184 65/72/177 -s 12 -f 94/106/185 53/60/179 66/73/182 93/105/186 -s 11 -f 27/34/187 44/51/188 69/76/189 67/74/190 -s 12 -f 57/64/191 55/62/192 68/75/193 70/77/194 -s off -f 44/51/195 40/47/196 71/78/197 69/76/198 -f 40/47/199 59/66/200 72/79/201 71/78/202 -s 12 -f 59/66/203 57/64/191 70/77/194 72/79/204 -s 13 -f 62/69/205 65/72/206 74/81/207 73/80/208 -s 14 -f 66/73/209 63/70/210 76/83/211 75/82/212 -s off -f 63/70/213 62/69/214 73/80/215 76/83/216 -s 13 -f 65/72/206 90/102/217 91/103/218 74/81/207 -s 14 -f 93/105/219 66/73/209 75/82/212 92/104/220 -s 13 -f 67/74/221 69/76/222 79/86/223 77/84/224 -s off -f 69/76/225 70/77/226 80/87/227 79/86/228 -s 14 -f 70/77/229 68/75/230 78/85/231 80/87/232 -s 8 -f 82/89/108 81/88/107 45/53/233 46/52/234 -s 2 -f 83/90/120 82/89/119 46/52/235 48/55/236 -s 6 -f 84/91/116 83/90/115 48/55/237 47/54/238 -s off -f 46/92/239 48/95/240 47/94/241 45/93/242 -s 2 -f 87/99/22 86/97/21 10/20/243 9/19/244 -f 88/100/55 87/98/22 9/9/244 31/38/245 -f 89/101/69 108/120/68 109/121/96 27/34/95 -s 11 -f 90/102/184 89/101/183 27/34/187 67/74/190 -s 13 -f 91/103/218 90/102/217 67/74/221 77/84/224 -s 9 -f 92/104/142 91/103/141 77/84/145 78/85/148 -s 14 -f 68/75/230 93/105/219 92/104/220 78/85/231 -s 12 -f 55/62/192 94/106/185 93/105/186 68/75/193 -s 3 -f 95/107/40 94/106/39 55/62/92 56/63/91 -s 10 -f 28/35/150 96/108/143 95/107/144 56/63/151 -s 1 -f 100/112/87 101/113/59 96/108/62 28/35/88 -s 15 -f 114/128/246 113/125/247 115/126/248 116/127/249 -f 117/129/250 113/125/247 114/128/246 118/130/251 -f 116/127/249 119/131/252 120/132/253 121/133/254 -f 116/127/249 115/126/248 122/134/255 119/131/252 -s 1 -f 97/109/58 29/36/54 102/114/60 101/113/59 -f 29/36/54 36/43/48 103/115/79 102/114/60 -f 36/43/48 35/42/47 104/116/80 103/115/79 -s 5 -f 35/42/52 34/41/51 105/117/76 104/116/75 -s 2 -f 34/41/46 33/40/45 106/118/71 105/117/73 -f 33/40/45 32/39/53 107/119/67 106/118/71 -f 32/39/53 88/100/55 108/120/68 107/119/67 -f 109/121/96 108/120/68 88/100/55 31/38/245 -f 110/122/97 109/121/96 31/38/245 43/50/118 -f 111/123/101 110/122/97 43/50/118 38/44/117 -s 6 -f 38/44/114 37/45/113 112/124/64 111/123/63 -s 1 -f 42/49/109 99/111/90 112/124/99 37/45/110 -s 16 -f 98/110/256 97/109/257 115/126/258 113/125/259 -s 4 -f 30/37/56 19/26/44 114/128/260 116/127/261 -s 16 -f 85/96/262 98/110/256 113/125/259 117/129/263 -s 4 -f 19/26/44 20/27/43 118/130/264 114/128/260 -s 16 -f 100/112/265 99/111/266 120/132/267 119/131/268 -s off -f 99/111/269 42/49/270 121/133/271 120/132/272 -s 7 -f 42/49/85 30/37/84 116/127/273 121/133/274 -s 16 -f 97/109/257 101/113/275 122/134/276 115/126/258 -f 101/113/275 100/112/265 119/131/268 122/134/276 -s 1 -f 11/135/1 14/138/4 129/137/277 128/136/278 -f 14/138/4 16/140/6 130/139/279 129/137/277 -f 16/140/6 18/142/8 131/141/280 130/139/279 -f 18/142/8 85/144/10 204/143/281 131/141/280 -s off -f 4/145/282 123/148/283 124/147/284 1/146/285 -s 18 -f 1/146/286 124/147/287 125/150/288 2/149/289 -f 2/149/289 125/150/288 126/152/290 3/151/291 -f 3/151/291 126/152/290 193/154/292 86/153/293 -s off -f 4/155/294 11/135/295 128/136/296 123/156/297 -f 123/156/298 128/136/299 129/137/300 124/157/301 -f 157/158/302 160/161/303 159/160/304 158/159/305 -s 19 -f 158/159/306 159/160/307 162/163/308 161/162/309 -f 161/162/309 162/163/308 201/165/310 200/164/311 -s 20 -f 127/166/312 132/169/313 20/168/314 10/167/315 -s 18 -f 124/157/287 146/172/316 145/171/317 125/170/288 -s 1 -f 130/139/279 148/174/318 147/173/319 129/137/277 -s 21 -f 129/137/320 147/173/321 146/172/322 124/157/323 -s 18 -f 125/170/288 145/171/317 144/176/324 126/175/290 -s 1 -f 131/141/280 141/177/325 148/174/318 130/139/279 -s 18 -f 126/175/290 144/176/324 194/179/326 193/178/292 -s 20 -f 127/166/312 143/181/327 142/180/328 132/169/313 -s 1 -f 204/143/281 203/182/329 141/177/325 131/141/280 -f 207/183/330 202/186/331 138/185/332 208/184/333 -s 23 -f 217/187/334 152/190/335 151/189/336 218/188/337 -s 18 -f 213/191/338 137/194/339 195/193/340 214/192/341 -f 212/195/342 134/196/343 137/194/339 213/191/338 -f 211/197/344 133/198/345 134/196/343 212/195/342 -s 21 -f 210/199/346 136/200/347 133/198/348 211/197/349 -s 1 -f 209/201/350 135/202/351 136/200/352 210/199/353 -f 208/184/333 138/185/332 135/202/351 209/201/350 -s 25 -f 143/181/354 155/204/355 154/203/356 142/180/357 -s 1 -f 206/205/358 205/208/359 153/207/360 140/206/361 -s 19 -f 164/209/362 166/212/363 165/211/364 163/210/365 -s 18 -f 139/213/366 156/216/367 216/215/368 215/214/369 -s 1 -f 218/188/370 151/189/371 153/207/360 205/208/359 -s off -f 46/217/372 48/220/373 47/219/374 45/218/375 -s 18 -f 156/216/367 152/190/376 217/187/377 216/215/368 -s 19 -f 166/212/363 168/222/378 167/221/379 165/211/364 -s 29 -f 155/204/380 190/224/381 189/223/382 154/203/383 -s 1 -f 154/203/384 189/223/385 192/226/386 149/225/387 -s 23 -f 149/225/388 192/226/389 191/228/390 150/227/391 -s 18 -f 150/227/392 191/228/393 190/224/394 155/204/395 -s off -f 169/229/396 172/232/397 171/231/398 170/230/399 -f 135/202/400 159/160/401 160/161/402 136/200/403 -f 136/200/404 160/161/405 157/158/406 133/198/407 -s 33 -f 181/233/408 184/236/409 183/235/410 182/234/411 -s 34 -f 138/185/412 162/163/413 159/160/414 135/202/415 -s 33 -f 182/234/411 183/235/410 198/238/416 197/237/417 -s 34 -f 202/186/418 201/165/419 162/163/413 138/185/412 -s 33 -f 185/239/420 186/242/421 188/241/422 187/240/423 -s 34 -f 153/207/424 166/212/425 164/209/426 140/206/427 -s off -f 177/243/428 178/246/429 180/245/430 179/244/431 -f 152/190/432 167/221/433 168/222/434 151/189/435 -s 34 -f 151/189/436 168/222/437 166/212/425 153/207/424 -s off -f 133/198/438 169/229/439 170/230/440 134/196/441 -f 158/159/442 171/231/443 172/232/444 157/158/445 -f 157/158/446 172/232/447 169/229/448 133/198/449 -s 36 -f 134/196/450 170/230/451 173/247/452 137/194/453 -s 37 -f 161/162/454 174/248/455 171/231/456 158/159/457 -s 36 -f 137/194/453 173/247/452 196/249/458 195/193/459 -s 37 -f 200/164/460 199/250/461 174/248/455 161/162/454 -s 36 -f 139/213/462 175/251/463 177/243/464 156/216/465 -s 37 -f 165/211/466 178/246/467 176/252/468 163/210/469 -s off -f 156/216/470 177/243/471 179/244/472 152/190/473 -f 152/190/474 179/244/475 180/245/476 167/221/477 -s 37 -f 167/221/478 180/245/479 178/246/467 165/211/466 -s 39 -f 170/230/480 181/233/481 182/234/482 173/247/483 -s 40 -f 174/248/484 183/235/485 184/236/486 171/231/487 -s off -f 171/231/488 184/236/489 181/233/490 170/230/491 -s 39 -f 173/247/483 182/234/482 197/237/492 196/249/493 -s 40 -f 199/250/494 198/238/495 183/235/485 174/248/484 -s 39 -f 175/251/496 185/239/497 187/240/498 177/243/499 -s off -f 177/243/500 187/240/501 188/241/502 178/246/503 -s 40 -f 178/246/504 188/241/505 186/242/506 176/252/507 -s 29 -f 190/224/381 46/217/508 45/218/509 189/223/382 -s 18 -f 191/228/393 48/220/510 46/217/511 190/224/394 -s 23 -f 192/226/389 47/219/512 48/220/513 191/228/390 -s 1 -f 189/223/385 45/218/514 47/219/515 192/226/386 -s off -f 46/253/516 45/256/517 47/255/518 48/254/519 -s 18 -f 193/154/292 127/258/520 10/257/521 86/153/293 -f 194/179/326 143/181/522 127/166/520 193/178/292 -f 195/193/340 139/213/366 215/214/369 214/192/341 -s 36 -f 196/249/458 175/251/463 139/213/462 195/193/459 -s 39 -f 197/237/492 185/239/497 175/251/496 196/249/493 -s 33 -f 198/238/416 186/242/421 185/239/420 197/237/417 -s 40 -f 176/252/507 186/242/506 198/238/495 199/250/494 -s 37 -f 163/210/469 176/252/468 199/250/461 200/164/460 -s 19 -f 201/165/310 164/209/362 163/210/365 200/164/311 -s 34 -f 140/206/427 164/209/426 201/165/419 202/186/418 -s 1 -f 206/205/358 140/206/361 202/186/331 207/183/330 -s 41 -f 220/259/523 222/262/524 221/261/525 219/260/526 -f 117/263/527 118/264/528 220/259/523 219/260/526 -f 222/262/524 225/267/529 224/266/530 223/265/531 -f 222/262/524 223/265/531 226/268/532 221/261/525 -s 1 -f 203/182/329 207/183/330 208/184/333 141/177/325 -f 141/177/325 208/184/333 209/201/350 148/174/318 -f 148/174/318 209/201/350 210/199/353 147/173/319 -s 21 -f 147/173/321 210/199/346 211/197/349 146/172/322 -s 18 -f 146/172/316 211/197/344 212/195/342 145/171/317 -f 145/171/317 212/195/342 213/191/338 144/176/324 -f 144/176/324 213/191/338 214/192/341 194/179/326 -f 215/214/369 143/181/522 194/179/326 214/192/341 -f 216/215/368 155/204/395 143/181/522 215/214/369 -f 217/187/377 150/227/392 155/204/395 216/215/368 -s 23 -f 150/227/391 217/187/334 218/188/337 149/225/388 -s 1 -f 154/203/384 149/225/387 218/188/370 205/208/359 -s 16 -f 204/143/533 219/260/534 221/261/535 203/182/536 -s 20 -f 142/180/328 222/262/537 220/259/538 132/169/313 -s 16 -f 85/144/262 117/263/263 219/260/534 204/143/533 -s 20 -f 132/169/313 220/259/538 118/264/539 20/168/314 -s 16 -f 206/205/540 223/265/541 224/266/542 205/208/543 -s off -f 205/208/544 224/266/545 225/267/546 154/203/547 -s 25 -f 154/203/356 225/267/548 222/262/549 142/180/357 -s 16 -f 203/182/536 221/261/535 226/268/550 207/183/551 -f 207/183/551 226/268/550 223/265/541 206/205/540 -s 1 -f 84/269/111 47/270/552 45/271/553 81/272/112 diff --git a/models/LightCycle_Chassis.obj b/models/LightCycle_Chassis.obj deleted file mode 100644 index 5739dea..0000000 --- a/models/LightCycle_Chassis.obj +++ /dev/null @@ -1,2130 +0,0 @@ -# This file uses centimeters as units for non-parametric coordinates. - -mtllib LightCycle_Chassis.mtl -g default -v 0.804108 0.764539 4.459316 -v 1.324199 1.296532 4.459316 -v -0.000384 1.655536 4.459316 -v 0.730730 1.605711 4.459316 -v -0.000384 1.886739 2.217480 -v 0.803803 1.836912 2.217480 -v 1.456619 1.296532 2.217480 -v 0.884519 0.764539 2.217480 -v -0.000384 0.416512 2.217480 -v 0.884519 0.416512 2.217480 -v -0.000384 0.416512 4.459316 -v 0.804108 0.416512 4.459316 -v 0.589156 0.943168 4.459316 -v 0.866751 1.273536 4.459316 -v -0.000384 1.477395 4.459316 -v 0.597233 1.477395 4.459316 -v -0.000384 0.755384 4.459316 -v 0.475897 0.755384 4.459316 -v -0.000384 1.084376 5.453352 -v -0.000384 1.169367 5.464950 -v 0.528543 1.084376 5.453352 -v 0.626439 1.169367 5.453352 -v -0.000384 1.306662 5.453352 -v 0.496645 1.306662 5.453352 -v -0.000384 1.021867 5.444889 -v 0.431587 1.021867 5.444889 -v 0.779445 1.762989 3.258170 -v -0.000384 1.812815 3.258170 -v -0.000384 0.416512 3.258170 -v 0.857715 0.416512 3.258170 -v 0.857715 0.764539 3.258170 -v 1.412479 1.296532 3.258170 -v 0.755087 1.684350 3.858743 -v -0.000384 1.734176 3.858743 -v -0.000384 0.416512 3.858743 -v 0.830911 0.416512 3.858743 -v 0.830911 0.764539 3.858743 -v 1.368339 1.296532 3.858743 -v 1.455033 0.724780 3.271559 -v 1.455033 0.724780 3.872133 -v 1.524235 0.504489 3.872664 -v 1.524235 0.504489 3.272091 -v 1.411219 0.917696 3.871601 -v 1.411219 0.917696 3.271027 -v 1.847108 0.724782 3.271559 -v 1.847108 0.724782 3.872133 -v 1.847108 0.504489 3.872664 -v 1.847108 0.504489 3.272091 -v -0.000384 1.758838 2.217480 -v 0.458742 1.568821 2.217480 -v 0.648759 1.110080 2.217480 -v 0.546633 0.863527 2.217480 -v -0.000384 0.461322 2.217480 -v 0.458742 0.651338 2.217480 -v -0.000384 1.758838 2.005543 -v 0.458742 1.568821 2.005543 -v 0.648759 1.110080 2.005543 -v 0.546633 0.863527 2.005543 -v -0.000384 0.461322 2.005543 -v 0.458742 0.651338 2.005543 -v -0.000384 1.758838 0.847391 -v 0.458742 1.568821 0.847391 -v 0.648759 1.110080 0.847391 -v 0.546633 0.863527 0.847391 -v -0.000384 0.461322 0.847391 -v 0.458742 0.651338 0.847391 -v -0.000384 1.797617 0.503059 -v 0.863139 1.655102 0.503059 -v 1.634925 1.296532 0.521120 -v 0.992793 0.764539 0.621681 -v -0.000384 0.461319 0.621681 -v 0.992793 0.461319 0.621681 -v -0.000384 1.797617 0.212019 -v 1.051070 1.711660 0.212019 -v 1.679455 1.296532 0.212019 -v 1.156616 0.764539 0.212019 -v -0.000384 0.461319 0.212019 -v 1.156616 0.461319 0.212019 -v -0.000384 1.797617 -0.283159 -v -0.000384 1.346357 -0.283158 -v 1.087222 1.711660 -0.283159 -v 1.634925 1.303627 -0.283159 -v -0.000384 0.796994 -0.283158 -v 1.182088 0.796994 -0.283159 -v -0.000384 0.461319 -0.283159 -v 1.131144 0.461319 -0.283159 -v -0.000384 0.461324 -3.984542 -v 1.855464 0.796998 -3.984542 -v 1.760234 0.461324 -3.984542 -v 1.855465 0.796996 -2.397152 -v -0.000384 0.796992 -2.397151 -v -0.000384 0.461322 -2.397152 -v 1.760235 0.461322 -2.397152 -v 1.855455 2.205541 -2.658255 -v -0.000384 2.205537 -2.658254 -v 1.855454 2.205543 -3.984540 -v -0.000384 2.205540 -3.984540 -v -0.000384 0.796993 -0.484668 -v -0.000384 0.461320 -0.484669 -v 1.754355 0.461320 -0.484669 -v 1.847751 0.796995 -0.484669 -v -0.000384 1.797617 -0.733662 -v -0.000384 1.346357 -0.733661 -v 1.005620 1.711659 -0.733662 -v 1.424341 1.303627 -0.733662 -v 0.995323 2.397264 -2.889951 -v -0.000384 2.397263 -2.889951 -v 0.995323 2.397266 -3.623426 -v -0.000384 2.397266 -3.623426 -v -0.000384 0.960971 -4.630631 -v -0.000384 0.736809 -4.630632 -v 1.245776 1.145234 -4.630632 -v 1.205786 0.736809 -4.630632 -v -0.000384 1.947926 -4.630630 -v 1.252432 1.947928 -4.630631 -v -0.000384 1.312207 -0.283158 -v -0.000384 0.836092 -0.283158 -v 1.515547 1.275174 -0.283159 -v 1.123088 0.836092 -0.283159 -v -0.000384 1.312207 0.387114 -v -0.000384 0.836092 0.387114 -v 1.515548 1.275174 0.387113 -v 1.123088 0.836092 0.387113 -v 0.458742 1.568821 1.015369 -v -0.000384 1.758838 1.015369 -v -0.000384 0.461322 1.015369 -v 0.458742 0.651338 1.015369 -v 0.546633 0.863527 1.015369 -v 0.648759 1.110080 1.015369 -v 2.123819 0.804595 1.638013 -v 2.123819 0.684550 1.638013 -v 2.123819 0.684550 0.716566 -v 2.123819 0.804595 0.716566 -v 3.040929 1.303514 1.460013 -v 3.143123 1.241566 1.460013 -v 3.143123 1.241566 0.469838 -v 3.040929 1.303514 0.469838 -v 3.040929 1.785769 1.460013 -v 3.143123 1.869436 1.460013 -v 3.143123 1.869436 0.469838 -v 3.040929 1.785769 0.469838 -v 2.942550 2.121625 1.592062 -v 2.942550 2.241928 1.592062 -v 2.942550 2.241928 0.601888 -v 2.942550 2.121625 0.601888 -v 2.094804 2.121625 1.592062 -v 2.094804 2.241928 1.592062 -v 2.094804 2.241928 0.601888 -v 2.094804 2.121625 0.601888 -v 2.333150 2.121625 -0.272189 -v 2.094804 2.121625 -0.272189 -v 2.094804 2.241928 -0.272189 -v 2.333150 2.241928 -0.272189 -v -0.804877 0.764539 4.459316 -v -1.324968 1.296532 4.459316 -v -0.731499 1.605711 4.459316 -v -0.804572 1.836912 2.217480 -v -1.457388 1.296532 2.217480 -v -0.885287 0.764539 2.217480 -v -0.885287 0.416512 2.217480 -v -0.804877 0.416512 4.459316 -v -0.589925 0.943168 4.459316 -v -0.867520 1.273536 4.459316 -v -0.598002 1.477395 4.459316 -v -0.476666 0.755384 4.459316 -v -0.529312 1.084376 5.453352 -v -0.627208 1.169367 5.453352 -v -0.497414 1.306662 5.453352 -v -0.432356 1.021867 5.444889 -v -0.780214 1.762989 3.258170 -v -0.858484 0.416512 3.258170 -v -0.858484 0.764539 3.258170 -v -1.413248 1.296532 3.258170 -v -0.755856 1.684350 3.858743 -v -0.831680 0.416512 3.858743 -v -0.831680 0.764539 3.858743 -v -1.369108 1.296532 3.858743 -v -1.455802 0.724780 3.271559 -v -1.455802 0.724780 3.872133 -v -1.525004 0.504489 3.872664 -v -1.525004 0.504489 3.272091 -v -1.411988 0.917696 3.871601 -v -1.411988 0.917696 3.271027 -v -1.847877 0.724782 3.271559 -v -1.847877 0.724782 3.872133 -v -1.847877 0.504489 3.872664 -v -1.847877 0.504489 3.272091 -v -0.459511 1.568821 2.217480 -v -0.649528 1.110080 2.217480 -v -0.547402 0.863527 2.217480 -v -0.459511 0.651338 2.217480 -v -0.459511 1.568821 2.005543 -v -0.649528 1.110080 2.005543 -v -0.547402 0.863527 2.005543 -v -0.459511 0.651338 2.005543 -v -0.459511 1.568821 0.847391 -v -0.649528 1.110080 0.847391 -v -0.547402 0.863527 0.847391 -v -0.459511 0.651338 0.847391 -v -0.863908 1.655102 0.503059 -v -1.635694 1.296532 0.521120 -v -0.993562 0.764539 0.621681 -v -0.993562 0.461319 0.621681 -v -1.051839 1.711660 0.212019 -v -1.680224 1.296532 0.212019 -v -1.157385 0.764539 0.212019 -v -1.157385 0.461319 0.212019 -v -1.087991 1.711660 -0.283159 -v -1.635694 1.303627 -0.283159 -v -1.182857 0.796994 -0.283159 -v -1.131913 0.461319 -0.283159 -v -1.856233 0.796998 -3.984542 -v -1.761003 0.461324 -3.984542 -v -1.856234 0.796996 -2.397152 -v -1.761004 0.461322 -2.397152 -v -1.856224 2.205541 -2.658255 -v -1.856223 2.205543 -3.984540 -v -1.755124 0.461320 -0.484669 -v -1.848520 0.796995 -0.484669 -v -1.006389 1.711659 -0.733662 -v -1.425110 1.303627 -0.733662 -v -0.996092 2.397264 -2.889951 -v -0.996092 2.397266 -3.623426 -v -1.246545 1.145234 -4.630632 -v -1.206554 0.736809 -4.630632 -v -1.253201 1.947928 -4.630631 -v -1.516316 1.275174 -0.283159 -v -1.123857 0.836092 -0.283159 -v -1.516316 1.275174 0.387113 -v -1.123857 0.836092 0.387113 -v -0.459511 1.568821 1.015369 -v -0.459511 0.651338 1.015369 -v -0.547402 0.863527 1.015369 -v -0.649528 1.110080 1.015369 -v -2.124588 0.804595 1.638013 -v -2.124588 0.684550 1.638013 -v -2.124588 0.684550 0.716566 -v -2.124588 0.804595 0.716566 -v -3.041698 1.303514 1.460013 -v -3.143892 1.241566 1.460013 -v -3.143892 1.241566 0.469838 -v -3.041698 1.303514 0.469838 -v -3.041698 1.785769 1.460013 -v -3.143892 1.869436 1.460013 -v -3.143892 1.869436 0.469838 -v -3.041698 1.785769 0.469838 -v -2.943319 2.121625 1.592062 -v -2.943319 2.241928 1.592062 -v -2.943319 2.241928 0.601888 -v -2.943319 2.121625 0.601888 -v -2.095573 2.121625 1.592062 -v -2.095573 2.241928 1.592062 -v -2.095573 2.241928 0.601888 -v -2.095573 2.121625 0.601888 -v -2.333919 2.121625 -0.272189 -v -2.095573 2.121625 -0.272189 -v -2.095573 2.241928 -0.272189 -v -2.333919 2.241928 -0.272189 -vt 0.500000 0.000000 -vt 0.625000 0.000000 -vt 0.500000 0.125000 -vt 0.625000 0.125000 -vt 0.500000 0.250000 -vt 0.625000 0.250000 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.625000 -vt 0.625000 0.625000 -vt 0.500000 0.750000 -vt 0.625000 0.781250 -vt 0.500000 0.781250 -vt 0.500000 1.000000 -vt 0.625000 1.000000 -vt 0.812500 0.000000 -vt 0.812500 0.125000 -vt 0.812500 0.250000 -vt 0.625000 0.781250 -vt 0.500000 1.000000 -vt 0.625000 1.000000 -vt 0.625000 0.000000 -vt 0.625000 0.125000 -vt 0.500000 0.250000 -vt 0.625000 0.250000 -vt 0.500000 1.000000 -vt 0.625000 1.000000 -vt 0.625000 1.000000 -vt 0.625000 0.000000 -vt 0.625000 0.125000 -vt 0.500000 0.250000 -vt 0.625000 0.250000 -vt 0.500000 1.000000 -vt 0.625000 1.000000 -vt 0.625000 1.000000 -vt 0.625000 0.333333 -vt 0.708333 0.250000 -vt 0.500000 0.333333 -vt 0.500000 0.916667 -vt 0.625000 0.916667 -vt 0.625000 0.916667 -vt 0.708333 0.000000 -vt 0.708333 0.125000 -vt 0.625000 0.291667 -vt 0.666667 0.250000 -vt 0.500000 0.291667 -vt 0.500000 0.958333 -vt 0.625000 0.958333 -vt 0.625000 0.958333 -vt 0.666667 0.000000 -vt 0.666667 0.125000 -vt 0.625000 0.958333 -vt 0.625000 0.958333 -vt 0.625000 0.916667 -vt 0.625000 0.916667 -vt 0.666667 0.125000 -vt 0.666667 0.000000 -vt 0.708333 0.000000 -vt 0.708333 0.125000 -vt 0.625000 0.916667 -vt 0.625000 0.958333 -vt 0.625000 0.958333 -vt 0.625000 0.916667 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.625000 -vt 0.625000 0.781250 -vt 0.500000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.625000 -vt 0.625000 0.781250 -vt 0.500000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.625000 -vt 0.625000 0.781250 -vt 0.500000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.625000 -vt 0.625000 0.781250 -vt 0.500000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.625000 -vt 0.625000 0.781250 -vt 0.500000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.625000 -vt 0.625000 0.781250 -vt 0.500000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.750000 -vt 0.500000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.750000 -vt 0.500000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.750000 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.750000 -vt 0.500000 0.750000 -vt 0.500000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.468750 -vt 0.500000 0.625000 -vt 0.625000 0.468750 -vt 0.625000 0.625000 -vt 0.500000 0.750000 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.750000 -vt 0.500000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.750000 -vt 0.625000 0.781250 -vt 0.500000 0.625000 -vt 0.500000 0.750000 -vt 0.625000 0.625000 -vt 0.625000 0.781250 -vt 0.500000 0.625000 -vt 0.500000 0.750000 -vt 0.625000 0.625000 -vt 0.625000 0.781250 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.500000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.625000 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.000000 -vt 0.625000 0.000000 -vt 0.625000 0.125000 -vt 0.500000 0.125000 -vt 0.625000 0.250000 -vt 0.500000 0.250000 -vt 0.500000 0.250000 -vt 0.625000 0.250000 -vt 0.625000 0.291667 -vt 0.500000 0.291667 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.625000 -vt 0.500000 0.625000 -vt 0.500000 0.625000 -vt 0.625000 0.625000 -vt 0.625000 0.781250 -vt 0.500000 0.750000 -vt 0.500000 0.958333 -vt 0.625000 0.958333 -vt 0.625000 1.000000 -vt 0.500000 1.000000 -vt 0.625000 0.000000 -vt 0.666667 0.000000 -vt 0.666667 0.125000 -vt 0.625000 0.125000 -vt 0.666667 0.250000 -vt 0.500000 0.750000 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.781250 -vt 0.625000 0.958333 -vt 0.625000 1.000000 -vt 0.625000 1.000000 -vt 0.500000 1.000000 -vt 0.500000 1.000000 -vt 0.625000 1.000000 -vt 0.625000 0.125000 -vt 0.625000 0.000000 -vt 0.625000 0.250000 -vt 0.500000 0.250000 -vt 0.625000 1.000000 -vt 0.500000 1.000000 -vt 0.625000 1.000000 -vt 0.500000 0.333333 -vt 0.625000 0.333333 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.500000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.916667 -vt 0.500000 0.916667 -vt 0.625000 0.781250 -vt 0.625000 0.916667 -vt 0.708333 0.125000 -vt 0.708333 0.000000 -vt 0.812500 0.000000 -vt 0.812500 0.125000 -vt 0.708333 0.250000 -vt 0.812500 0.250000 -vt 0.625000 0.916667 -vt 0.625000 0.958333 -vt 0.625000 0.958333 -vt 0.625000 0.916667 -vt 0.666667 0.125000 -vt 0.666667 0.000000 -vt 0.708333 0.000000 -vt 0.708333 0.125000 -vt 0.625000 0.958333 -vt 0.625000 0.958333 -vt 0.625000 0.916667 -vt 0.625000 0.916667 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.625000 -vt 0.625000 0.625000 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.781250 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.625000 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.781250 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.625000 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.468750 -vt 0.625000 0.468750 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.625000 -vt 0.625000 0.625000 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.781250 -vt 0.500000 0.781250 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.625000 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.781250 -vt 0.625000 0.468750 -vt 0.500000 0.468750 -vt 0.625000 0.625000 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.781250 -vt 0.500000 0.750000 -vt 0.625000 0.781250 -vt 0.500000 0.750000 -vt 0.625000 0.781250 -vt 0.500000 0.781250 -vt 0.500000 0.750000 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.750000 -vt 0.625000 0.781250 -vt 0.500000 0.781250 -vt 0.500000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.500000 0.750000 -vt 0.625000 0.781250 -vt 0.500000 0.750000 -vt 0.625000 0.781250 -vt 0.500000 0.750000 -vt 0.625000 0.781250 -vt 0.500000 0.625000 -vt 0.500000 0.750000 -vt 0.625000 0.625000 -vt 0.500000 0.625000 -vt 0.625000 0.781250 -vt 0.500000 0.750000 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vt 0.625000 0.781250 -vn 0.005006 -0.104035 0.994561 -vn 0.005006 -0.104035 0.994561 -vn 0.010176 -0.013396 0.999859 -vn 0.010176 -0.013396 0.999859 -vn 0.010307 0.047059 0.998839 -vn 0.010307 0.047059 0.998839 -vn 0.066308 0.989180 0.130868 -vn 0.066308 0.989180 0.130868 -vn 0.065261 0.989251 0.130857 -vn 0.065261 0.989251 0.130857 -vn -0.000000 -0.000001 -1.000000 -vn -0.000000 -0.000001 -1.000000 -vn -0.000000 -0.000001 -1.000000 -vn -0.000000 -0.000001 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.042834 -0.999082 0.000956 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.708637 -0.704331 0.041854 -vn 0.708637 -0.704331 0.041854 -vn 0.933204 0.349375 0.084066 -vn 0.986158 0.129481 0.103570 -vn 0.531215 0.842914 0.085479 -vn 0.498353 0.862806 0.084908 -vn -0.000001 0.000001 -1.000000 -vn -0.000001 0.000001 -1.000000 -vn -0.000001 0.000001 -1.000000 -vn -0.000001 0.000001 -1.000000 -vn 0.999006 0.000000 0.044586 -vn 0.999006 0.000000 0.044586 -vn 0.999006 0.000000 0.044586 -vn 0.999006 0.000000 0.044586 -vn 0.000000 -0.134171 0.990958 -vn 0.000000 -0.134171 0.990958 -vn 0.000000 0.000000 1.000000 -vn -0.000000 0.000000 1.000000 -vn -0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn -0.000000 0.000000 1.000000 -vn -0.000000 0.000000 1.000000 -vn -0.000001 0.000000 1.000000 -vn -0.000001 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.744163 -0.651513 0.147486 -vn 0.736103 -0.665449 0.123818 -vn 0.736103 -0.665449 0.123818 -vn 0.744163 -0.651513 0.147486 -vn 0.634857 0.743086 0.211611 -vn 0.634857 0.743086 0.211611 -vn 0.634857 0.743086 0.211611 -vn 0.634857 0.743086 0.211611 -vn 0.000000 0.985568 0.169278 -vn 0.000000 0.985568 0.169278 -vn 0.000000 0.985568 0.169278 -vn 0.000000 0.985568 0.169278 -vn 0.000000 -0.965336 0.261011 -vn 0.000000 -0.965336 0.261011 -vn 0.000000 -0.965336 0.261011 -vn 0.000000 -0.965336 0.261011 -vn 0.751614 -0.637043 0.171033 -vn 0.751614 -0.637043 0.171033 -vn 0.063448 0.992842 0.101190 -vn 0.063448 0.992842 0.101190 -vn 0.062627 0.995477 0.071445 -vn 0.062627 0.995477 0.071445 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.042834 -0.999082 0.000956 -vn 0.000000 -1.000000 0.000000 -vn 0.999669 0.000000 0.025747 -vn 0.999669 0.000000 0.025747 -vn 0.999669 0.000000 0.025747 -vn 0.999669 0.000000 0.025747 -vn 0.948398 0.310491 0.064321 -vn 0.686341 -0.726903 0.023394 -vn 0.686341 -0.726903 0.023394 -vn 0.997453 0.045603 0.054839 -vn 0.589942 0.804653 0.067106 -vn 0.615789 0.786435 0.048197 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 0.975166 0.221476 0.000000 -vn 0.975166 0.221476 0.000000 -vn 0.975166 0.221476 0.000000 -vn 0.975166 0.221476 0.000000 -vn -0.023951 0.008848 0.999674 -vn -0.020668 -0.001581 0.999785 -vn -0.010335 0.000416 0.999947 -vn -0.015968 0.006704 0.999850 -vn 0.064265 -0.997932 0.001434 -vn 0.064265 -0.997932 0.001434 -vn 0.021540 0.001688 -0.999767 -vn 0.025317 -0.009776 -0.999632 -vn 0.016879 -0.007322 -0.999831 -vn 0.010771 -0.000363 -0.999942 -vn -0.027232 0.019276 0.999443 -vn -0.027232 0.019276 0.999443 -vn 0.029091 -0.021238 -0.999351 -vn 0.029091 -0.021238 -0.999351 -vn 0.997755 0.056051 0.036666 -vn 0.997755 0.056051 0.036666 -vn -0.000004 1.000000 0.000000 -vn -0.000004 1.000000 0.000000 -vn -0.000004 1.000000 0.000000 -vn -0.000004 1.000000 0.000000 -vn -0.000000 0.002413 0.999997 -vn -0.000000 0.002413 0.999997 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -0.002413 -0.999997 -vn 0.000000 -0.002413 -0.999997 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.382410 0.923993 0.000001 -vn 0.382410 0.923993 0.000001 -vn 0.382410 0.923993 0.000000 -vn 0.382410 0.923993 0.000000 -vn 0.923880 0.382684 0.000001 -vn 0.923880 0.382684 0.000001 -vn 0.923879 0.382684 0.000001 -vn 0.923879 0.382684 0.000001 -vn 0.923879 -0.382684 0.000001 -vn 0.923879 -0.382684 0.000001 -vn 0.923879 -0.382684 0.000000 -vn 0.923879 -0.382684 0.000000 -vn 0.923879 -0.382684 0.000000 -vn 0.923879 -0.382684 0.000000 -vn 0.382409 -0.923993 0.000000 -vn 0.382409 -0.923993 0.000000 -vn 0.382410 -0.923993 0.000000 -vn 0.382410 -0.923993 0.000000 -vn 0.382410 0.923993 0.000000 -vn 0.382410 0.923993 0.000000 -vn 0.923879 0.382684 0.000000 -vn 0.923879 0.382684 0.000000 -vn 0.923879 -0.382684 0.000000 -vn 0.923879 -0.382684 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 -0.000001 -0.000000 -vn -1.000000 -0.000001 -0.000000 -vn 0.382410 -0.923993 0.000000 -vn 0.382410 -0.923993 0.000000 -vn 0.311859 0.937512 0.154319 -vn 0.311859 0.937512 0.154319 -vn 0.232273 0.923868 0.304167 -vn 0.232273 0.923868 0.304167 -vn 0.733727 0.462346 0.497877 -vn 0.733727 0.462346 0.497877 -vn 0.330511 0.407750 0.851177 -vn 0.330511 0.407750 0.851177 -vn 0.762475 -0.362970 0.535617 -vn 0.778413 -0.317028 0.541818 -vn 0.382725 -0.149440 0.911696 -vn 0.362167 -0.229527 0.903411 -vn 0.792603 -0.269885 0.546757 -vn 0.400639 -0.068320 0.913685 -vn 0.258164 -0.930868 0.258525 -vn 0.258164 -0.930868 0.258525 -vn 0.112667 -0.861115 0.495769 -vn 0.112667 -0.861115 0.495769 -vn 0.117407 0.984067 0.133524 -vn 0.117407 0.984067 0.133524 -vn 0.098989 0.992736 0.068384 -vn 0.098989 0.992736 0.068384 -vn 0.464484 0.846645 0.259704 -vn 0.464484 0.846645 0.259704 -vn 0.524187 0.841361 0.131677 -vn 0.524187 0.841361 0.131677 -vn 0.670610 -0.715886 0.194394 -vn 0.670610 -0.715886 0.194394 -vn 0.704714 -0.705289 0.077110 -vn 0.704714 -0.705289 0.077110 -vn 0.928510 0.000000 0.371308 -vn 0.928510 0.000000 0.371308 -vn 0.981347 -0.040513 0.187928 -vn 0.981347 -0.040513 0.187928 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -1.000000 -0.000000 -vn -0.000000 -1.000000 -0.000000 -vn -0.000000 -1.000000 -0.000000 -vn 0.080974 0.996714 -0.002244 -vn 0.080974 0.996714 -0.002244 -vn 0.606320 0.788583 -0.102538 -vn 0.606320 0.788583 -0.102538 -vn 0.728226 -0.684090 -0.041333 -vn 0.728226 -0.684090 -0.041333 -vn 0.803071 -0.089023 0.589195 -vn 0.803071 -0.089023 0.589195 -vn -0.000000 -1.000000 -0.000003 -vn -0.000000 -1.000000 -0.000003 -vn -0.000001 1.000000 -0.000001 -vn -0.000001 1.000000 -0.000001 -vn -0.000001 1.000000 -0.000000 -vn -0.000001 1.000000 -0.000000 -vn 0.779571 -0.206881 0.591160 -vn 0.779571 -0.206881 0.591160 -vn -0.000000 -1.000000 -0.000003 -vn -0.000000 -1.000000 -0.000003 -vn -0.000000 1.000000 0.000004 -vn 0.109437 0.993994 0.000003 -vn 0.109437 0.993994 0.000003 -vn -0.000000 1.000000 0.000004 -vn 0.000000 -1.000000 -0.000001 -vn 0.000000 -1.000000 -0.000001 -vn 0.000000 -0.979763 -0.200163 -vn 0.000000 -0.979763 -0.200163 -vn 0.983174 -0.182670 0.001150 -vn 0.962378 -0.271709 0.001710 -vn 0.962035 -0.272927 -0.000001 -vn 0.990464 -0.137774 -0.000001 -vn -0.000000 0.182265 0.983249 -vn -0.000000 0.182265 0.983249 -vn -0.000001 0.506746 0.862096 -vn -0.000001 0.506746 0.862096 -vn 1.000000 0.000007 -0.000000 -vn 1.000000 0.000007 -0.000000 -vn -0.000001 0.000001 -1.000000 -vn -0.000001 0.000001 -1.000000 -vn -0.000002 1.000000 -0.000000 -vn -0.000002 1.000000 -0.000000 -vn 0.081836 0.996618 -0.007413 -vn 0.081836 0.996618 -0.007413 -vn 0.631495 0.747847 -0.204788 -vn 0.631495 0.747847 -0.204788 -vn -0.027916 -0.999589 0.006525 -vn -0.027916 -0.999589 0.006525 -vn -0.027916 -0.999589 0.006525 -vn -0.027916 -0.999589 0.006525 -vn -0.000001 0.770434 0.637520 -vn -0.000001 0.770434 0.637520 -vn 0.217560 0.976047 0.000002 -vn 0.217560 0.976047 0.000002 -vn -0.000001 0.883234 -0.468933 -vn -0.000001 0.883234 -0.468933 -vn -0.000001 0.883234 -0.468933 -vn -0.000001 0.883234 -0.468933 -vn 0.718678 -0.065314 -0.692269 -vn 0.705275 -0.128165 -0.697253 -vn 0.705275 -0.128165 -0.697253 -vn 0.718678 -0.065314 -0.692269 -vn 0.000000 -0.919870 -0.392222 -vn 0.000000 -0.919870 -0.392222 -vn -0.000001 0.928884 -0.370371 -vn -0.000001 0.928884 -0.370371 -vn -0.000001 0.928884 -0.370371 -vn -0.000001 0.928884 -0.370371 -vn 0.729095 -0.002191 -0.684409 -vn 0.729095 -0.002191 -0.684409 -vn -0.000000 0.000001 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn -0.000000 0.000001 -1.000000 -vn -0.000000 -0.000000 -1.000000 -vn -0.000000 -0.000000 -1.000000 -vn -0.000001 -0.000000 -1.000000 -vn -0.000001 -0.000000 -1.000000 -vn -0.024422 -0.999702 0.000000 -vn -0.024422 -0.999702 0.000000 -vn -0.024422 -0.999702 0.000000 -vn -0.024422 -0.999702 0.000000 -vn -0.745582 0.666414 0.000000 -vn -0.745582 0.666414 0.000000 -vn -0.745582 0.666414 0.000000 -vn -0.745582 0.666414 0.000000 -vn 0.000000 1.000000 0.000000 -vn 0.000000 1.000000 0.000000 -vn 0.000000 1.000000 0.000000 -vn 0.000000 1.000000 0.000000 -vn 0.923879 -0.382684 0.000000 -vn 0.220286 -0.058276 0.973693 -vn 0.220286 -0.058276 0.973693 -vn 0.180190 0.009905 0.983582 -vn 0.180190 0.009905 0.983582 -vn 0.019942 -0.999801 0.000000 -vn 0.019942 -0.999801 0.000000 -vn 0.257115 -0.966381 0.000000 -vn 0.257115 -0.966381 0.000000 -vn -0.180690 0.047801 -0.982378 -vn -0.180690 0.047801 -0.982378 -vn -0.186098 -0.029642 -0.982084 -vn -0.186098 -0.029642 -0.982084 -vn 0.037339 0.999303 0.000000 -vn 0.037339 0.999303 0.000000 -vn -0.228409 0.973565 0.000000 -vn -0.228409 0.973565 0.000000 -vn 0.069698 0.039137 0.996800 -vn 0.069698 0.039137 0.996800 -vn 0.479537 -0.877521 0.000000 -vn 0.479537 -0.877521 0.000000 -vn -0.095772 -0.053778 -0.993950 -vn -0.095772 -0.053778 -0.993950 -vn -0.477876 0.878428 0.000000 -vn -0.477876 0.878428 0.000000 -vn 0.188267 -0.094327 0.977578 -vn 0.188267 -0.094327 0.977578 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn -0.188267 0.094327 -0.977578 -vn -0.188267 0.094327 -0.977578 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn 0.368090 -0.184423 0.911317 -vn 0.368090 -0.184423 0.911317 -vn 0.880471 0.474100 0.000000 -vn 0.880471 0.474100 0.000000 -vn 0.880471 0.474100 0.000000 -vn 0.880471 0.474100 0.000000 -vn -0.368091 0.184424 -0.911316 -vn -0.368091 0.184424 -0.911316 -vn -0.959676 -0.281108 0.000000 -vn -0.959676 -0.281108 0.000000 -vn -0.959676 -0.281108 0.000000 -vn -0.959676 -0.281108 0.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 1.000000 0.000000 -vn 0.000000 1.000000 0.000000 -vn 0.000000 1.000000 0.000000 -vn 0.000000 1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn -1.000000 -0.000002 -0.000000 -vn -1.000000 -0.000002 -0.000000 -vn 0.000000 1.000000 0.000000 -vn 0.000000 1.000000 0.000000 -vn 0.820312 -0.000002 -0.571916 -vn 0.820312 -0.000002 -0.571916 -vn 0.820312 -0.000002 -0.571916 -vn 0.820312 -0.000002 -0.571916 -vn -0.005006 -0.104035 0.994561 -vn -0.010176 -0.013396 0.999859 -vn -0.010176 -0.013396 0.999859 -vn -0.005006 -0.104035 0.994561 -vn -0.010307 0.047059 0.998839 -vn -0.010307 0.047059 0.998839 -vn -0.066308 0.989180 0.130868 -vn -0.065261 0.989251 0.130857 -vn -0.065261 0.989251 0.130857 -vn -0.066308 0.989180 0.130868 -vn 0.000000 -0.000001 -1.000000 -vn 0.000000 -0.000001 -1.000000 -vn 0.000000 -0.000001 -1.000000 -vn 0.000000 -0.000001 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn -0.042834 -0.999082 0.000956 -vn -0.708637 -0.704331 0.041854 -vn -0.986158 0.129481 0.103570 -vn -0.933204 0.349375 0.084066 -vn -0.708637 -0.704331 0.041854 -vn -0.498353 0.862806 0.084908 -vn -0.531215 0.842914 0.085479 -vn 0.000001 0.000001 -1.000000 -vn 0.000001 0.000001 -1.000000 -vn 0.000001 0.000001 -1.000000 -vn 0.000001 0.000001 -1.000000 -vn -0.999006 0.000000 0.044586 -vn -0.999006 0.000000 0.044586 -vn -0.999006 0.000000 0.044586 -vn -0.999006 0.000000 0.044586 -vn 0.000000 -0.134171 0.990958 -vn 0.000000 -0.134171 0.990958 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn -0.744163 -0.651513 0.147486 -vn -0.744163 -0.651513 0.147486 -vn -0.736103 -0.665449 0.123818 -vn -0.736103 -0.665449 0.123818 -vn -0.634857 0.743086 0.211611 -vn -0.634857 0.743086 0.211611 -vn -0.634857 0.743086 0.211611 -vn -0.634857 0.743086 0.211611 -vn 0.000000 0.985568 0.169278 -vn 0.000000 0.985568 0.169278 -vn 0.000000 0.985568 0.169278 -vn 0.000000 0.985568 0.169278 -vn 0.000000 -0.965336 0.261011 -vn 0.000000 -0.965336 0.261011 -vn 0.000000 -0.965336 0.261011 -vn 0.000000 -0.965336 0.261011 -vn -0.751614 -0.637044 0.171033 -vn -0.751614 -0.637044 0.171033 -vn -0.063448 0.992842 0.101190 -vn -0.062627 0.995477 0.071445 -vn -0.062627 0.995477 0.071445 -vn -0.063448 0.992842 0.101190 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn -0.042834 -0.999082 0.000956 -vn 0.000000 -1.000000 0.000000 -vn -0.999669 0.000000 0.025747 -vn -0.999669 0.000000 0.025747 -vn -0.999669 0.000000 0.025747 -vn -0.999669 0.000000 0.025747 -vn -0.948398 0.310491 0.064321 -vn -0.997453 0.045603 0.054840 -vn -0.686341 -0.726903 0.023394 -vn -0.686341 -0.726903 0.023394 -vn -0.589942 0.804653 0.067106 -vn -0.615789 0.786436 0.048197 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -0.975166 0.221476 0.000000 -vn -0.975166 0.221476 0.000000 -vn -0.975166 0.221476 0.000000 -vn -0.975166 0.221476 0.000000 -vn 0.023951 0.008848 0.999674 -vn 0.015968 0.006704 0.999850 -vn 0.010334 0.000416 0.999947 -vn 0.020668 -0.001581 0.999785 -vn -0.064265 -0.997932 0.001434 -vn -0.064265 -0.997932 0.001434 -vn -0.021540 0.001688 -0.999767 -vn -0.010771 -0.000363 -0.999942 -vn -0.016879 -0.007322 -0.999831 -vn -0.025317 -0.009776 -0.999632 -vn 0.027232 0.019276 0.999443 -vn 0.027232 0.019276 0.999443 -vn -0.029091 -0.021238 -0.999351 -vn -0.029091 -0.021238 -0.999351 -vn -0.997755 0.056051 0.036666 -vn -0.997755 0.056051 0.036666 -vn 0.000004 1.000000 0.000000 -vn 0.000004 1.000000 0.000000 -vn 0.000004 1.000000 0.000000 -vn 0.000004 1.000000 0.000000 -vn 0.000000 0.002413 0.999997 -vn 0.000000 0.002413 0.999997 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -0.002413 -0.999997 -vn 0.000000 -0.002413 -0.999997 -vn -0.000000 0.000000 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn -0.382410 0.923993 0.000001 -vn -0.382410 0.923993 0.000000 -vn -0.382410 0.923993 0.000000 -vn -0.382410 0.923993 0.000001 -vn -0.923879 0.382684 0.000001 -vn -0.923879 0.382684 0.000001 -vn -0.923879 0.382684 0.000001 -vn -0.923879 0.382684 0.000001 -vn -0.923879 -0.382684 0.000001 -vn -0.923879 -0.382684 0.000000 -vn -0.923879 -0.382684 0.000000 -vn -0.923879 -0.382684 0.000001 -vn -0.923879 -0.382684 0.000000 -vn -0.923879 -0.382684 0.000000 -vn -0.382409 -0.923993 0.000000 -vn -0.382410 -0.923993 0.000000 -vn -0.382410 -0.923993 0.000000 -vn -0.382409 -0.923993 0.000000 -vn -0.382410 0.923993 0.000000 -vn -0.382410 0.923993 0.000000 -vn -0.923879 0.382684 0.000000 -vn -0.923879 0.382684 0.000000 -vn -0.923879 -0.382684 0.000000 -vn -0.923879 -0.382684 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 -0.000000 -vn 1.000000 0.000000 -0.000000 -vn 1.000000 0.000000 0.000000 -vn -0.382410 -0.923993 0.000000 -vn -0.382410 -0.923993 0.000000 -vn -0.311859 0.937512 0.154319 -vn -0.232273 0.923868 0.304167 -vn -0.232273 0.923868 0.304167 -vn -0.311859 0.937512 0.154319 -vn -0.733727 0.462346 0.497877 -vn -0.330511 0.407750 0.851177 -vn -0.330511 0.407750 0.851177 -vn -0.733727 0.462346 0.497877 -vn -0.762475 -0.362970 0.535617 -vn -0.362168 -0.229527 0.903411 -vn -0.382725 -0.149440 0.911696 -vn -0.778413 -0.317028 0.541818 -vn -0.400639 -0.068320 0.913685 -vn -0.792603 -0.269885 0.546757 -vn -0.258164 -0.930868 0.258525 -vn -0.112667 -0.861115 0.495769 -vn -0.112667 -0.861115 0.495769 -vn -0.258164 -0.930868 0.258525 -vn -0.117407 0.984067 0.133524 -vn -0.098989 0.992736 0.068384 -vn -0.098989 0.992736 0.068384 -vn -0.117407 0.984067 0.133524 -vn -0.464484 0.846645 0.259705 -vn -0.524187 0.841361 0.131677 -vn -0.524187 0.841361 0.131677 -vn -0.464484 0.846645 0.259705 -vn -0.670610 -0.715886 0.194394 -vn -0.704714 -0.705289 0.077110 -vn -0.704714 -0.705289 0.077110 -vn -0.670610 -0.715886 0.194394 -vn -0.928510 0.000000 0.371308 -vn -0.981347 -0.040513 0.187928 -vn -0.981347 -0.040513 0.187928 -vn -0.928510 0.000000 0.371308 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -1.000000 -0.000000 -vn -0.080974 0.996714 -0.002244 -vn -0.080974 0.996714 -0.002244 -vn -0.606320 0.788583 -0.102538 -vn -0.606320 0.788583 -0.102538 -vn -0.728226 -0.684090 -0.041333 -vn -0.728226 -0.684090 -0.041333 -vn -0.803071 -0.089023 0.589195 -vn -0.803071 -0.089023 0.589195 -vn 0.000000 -1.000000 -0.000003 -vn 0.000000 -1.000000 -0.000003 -vn 0.000001 1.000000 -0.000001 -vn 0.000001 1.000000 -0.000001 -vn 0.000001 1.000000 -0.000001 -vn 0.000001 1.000000 -0.000001 -vn -0.779571 -0.206881 0.591160 -vn -0.779571 -0.206881 0.591160 -vn 0.000000 -1.000000 -0.000003 -vn 0.000000 -1.000000 -0.000003 -vn 0.000000 1.000000 0.000004 -vn 0.000000 1.000000 0.000004 -vn -0.109437 0.993994 0.000003 -vn -0.109437 0.993994 0.000003 -vn -0.000000 -1.000000 -0.000001 -vn -0.000000 -0.979763 -0.200163 -vn -0.000000 -0.979763 -0.200163 -vn -0.000000 -1.000000 -0.000001 -vn -0.983174 -0.182670 0.001150 -vn -0.990464 -0.137774 -0.000001 -vn -0.962035 -0.272926 -0.000001 -vn -0.962378 -0.271708 0.001710 -vn 0.000000 0.182265 0.983249 -vn 0.000001 0.506746 0.862096 -vn 0.000001 0.506746 0.862096 -vn 0.000000 0.182265 0.983249 -vn -1.000000 0.000007 -0.000000 -vn -1.000000 0.000007 -0.000000 -vn 0.000001 0.000001 -1.000000 -vn 0.000001 0.000001 -1.000000 -vn 0.000002 1.000000 -0.000000 -vn 0.000002 1.000000 -0.000000 -vn -0.081836 0.996618 -0.007413 -vn -0.081836 0.996618 -0.007413 -vn -0.631495 0.747847 -0.204787 -vn -0.631495 0.747847 -0.204787 -vn 0.027916 -0.999589 0.006525 -vn 0.027916 -0.999589 0.006525 -vn 0.027916 -0.999589 0.006525 -vn 0.027916 -0.999589 0.006525 -vn 0.000001 0.770434 0.637520 -vn 0.000001 0.770434 0.637520 -vn -0.217561 0.976047 0.000002 -vn -0.217561 0.976047 0.000002 -vn 0.000001 0.883234 -0.468933 -vn 0.000001 0.883234 -0.468933 -vn 0.000001 0.883234 -0.468933 -vn 0.000001 0.883234 -0.468933 -vn -0.718678 -0.065314 -0.692269 -vn -0.718678 -0.065314 -0.692269 -vn -0.705275 -0.128165 -0.697253 -vn -0.705275 -0.128165 -0.697253 -vn -0.000000 -0.919870 -0.392222 -vn -0.000000 -0.919870 -0.392222 -vn 0.000001 0.928884 -0.370372 -vn 0.000001 0.928884 -0.370372 -vn 0.000001 0.928884 -0.370372 -vn 0.000001 0.928884 -0.370372 -vn -0.729095 -0.002191 -0.684409 -vn -0.729095 -0.002191 -0.684409 -vn 0.000000 0.000001 -1.000000 -vn 0.000000 0.000001 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 -0.000000 -1.000000 -vn 0.000000 -0.000000 -1.000000 -vn 0.000001 -0.000000 -1.000000 -vn 0.000001 -0.000000 -1.000000 -vn 0.024422 -0.999702 0.000000 -vn 0.024422 -0.999702 0.000000 -vn 0.024422 -0.999702 0.000000 -vn 0.024422 -0.999702 0.000000 -vn 0.745582 0.666414 0.000000 -vn 0.745582 0.666414 0.000000 -vn 0.745582 0.666414 0.000000 -vn 0.745582 0.666414 0.000000 -vn -0.000000 1.000000 0.000000 -vn -0.000000 1.000000 0.000000 -vn -0.000000 1.000000 0.000000 -vn -0.000000 1.000000 0.000000 -vn -0.923879 -0.382684 0.000000 -vn -0.220286 -0.058276 0.973693 -vn -0.180190 0.009905 0.983582 -vn -0.180190 0.009905 0.983582 -vn -0.220286 -0.058276 0.973693 -vn -0.019942 -0.999801 0.000000 -vn -0.257115 -0.966381 0.000000 -vn -0.257115 -0.966381 0.000000 -vn -0.019942 -0.999801 0.000000 -vn 0.180690 0.047801 -0.982378 -vn 0.186098 -0.029642 -0.982084 -vn 0.186098 -0.029642 -0.982084 -vn 0.180690 0.047801 -0.982378 -vn -0.037339 0.999303 0.000000 -vn 0.228409 0.973565 0.000000 -vn 0.228409 0.973565 0.000000 -vn -0.037339 0.999303 0.000000 -vn -0.069698 0.039137 0.996800 -vn -0.069698 0.039137 0.996800 -vn -0.479537 -0.877521 0.000000 -vn -0.479537 -0.877521 0.000000 -vn 0.095772 -0.053778 -0.993950 -vn 0.095772 -0.053778 -0.993950 -vn 0.477875 0.878428 0.000000 -vn 0.477875 0.878428 0.000000 -vn -0.188267 -0.094327 0.977578 -vn -0.188267 -0.094327 0.977578 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn 0.188267 0.094328 -0.977578 -vn 0.188267 0.094328 -0.977578 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn -0.368090 -0.184425 0.911316 -vn -0.368090 -0.184425 0.911316 -vn -0.880471 0.474100 0.000000 -vn -0.880471 0.474100 0.000000 -vn -0.880471 0.474100 0.000000 -vn -0.880471 0.474100 0.000000 -vn 0.368091 0.184425 -0.911316 -vn 0.368091 0.184425 -0.911316 -vn 0.959676 -0.281108 0.000000 -vn 0.959676 -0.281108 0.000000 -vn 0.959676 -0.281108 0.000000 -vn 0.959676 -0.281108 0.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 1.000000 0.000000 -vn 0.000000 1.000000 0.000000 -vn 0.000000 1.000000 0.000000 -vn 0.000000 1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 1.000000 0.000000 -0.000000 -vn 1.000000 0.000000 -0.000000 -vn 0.000000 1.000000 0.000000 -vn 0.000000 1.000000 0.000000 -vn -0.820312 -0.000002 -0.571916 -vn -0.820312 -0.000002 -0.571916 -vn -0.820312 -0.000002 -0.571916 -vn -0.820312 -0.000002 -0.571916 -s 1 -g Chassis -usemtl initialShadingGroup -f 19/1/1 21/29/2 22/30/3 20/3/4 -f 20/3/4 22/30/3 24/32/5 23/31/6 -s 2 -f 3/5/7 4/6/8 33/44/9 34/46/10 -s off -f 102/116/11 104/118/12 105/119/13 103/117/14 -f 120/133/15 122/135/16 123/136/17 121/134/18 -s 3 -f 35/47/19 36/48/20 12/21/21 11/20/22 -s 4 -f 1/2/23 37/50/24 38/51/25 2/4/26 -f 2/4/26 38/51/25 33/45/27 4/6/28 -s 5 -f 110/100/29 112/125/30 113/126/31 111/124/32 -s off -f 37/49/33 1/15/34 12/21/35 36/48/36 -s 1 -f 21/35/2 19/14/1 25/33/37 26/34/38 -s 6 -f 1/2/39 2/4/40 14/23/41 13/22/42 -f 2/4/40 4/6/43 16/25/44 14/23/41 -f 4/6/43 3/5/45 15/24/46 16/25/44 -f 11/20/47 12/21/48 18/27/49 17/26/50 -f 12/21/48 1/15/39 13/28/42 18/27/49 -s 7 -f 13/22/51 14/23/52 22/30/53 21/29/54 -s off -f 14/23/55 16/25/56 24/32/57 22/30/58 -f 16/25/59 15/24/60 23/31/61 24/32/62 -f 17/26/63 18/27/64 26/34/65 25/33/66 -s 7 -f 18/27/67 13/28/51 21/35/54 26/34/68 -s 2 -f 28/38/69 27/36/70 6/8/71 5/7/72 -s 3 -f 9/13/73 10/19/74 30/40/75 29/39/76 -s off -f 8/12/77 31/41/78 30/40/79 10/19/80 -s 4 -f 32/43/81 31/42/82 8/16/83 7/17/84 -f 27/37/85 32/43/81 7/17/84 6/18/86 -s 2 -f 34/46/10 33/44/9 27/36/70 28/38/69 -s 3 -f 29/39/76 30/40/75 36/48/20 35/47/19 -s off -f 45/60/87 46/61/88 47/62/89 48/63/90 -f 43/56/91 40/57/92 39/58/93 44/59/94 -s 4 -f 33/45/27 38/51/25 32/43/81 27/37/85 -s 9 -f 37/49/95 36/48/96 41/53/97 40/52/98 -s 3 -f 36/48/20 30/40/75 42/54/99 41/53/100 -s 10 -f 30/40/101 31/41/102 39/55/103 42/54/104 -s 9 -f 38/51/105 37/50/95 40/57/98 43/56/106 -s 10 -f 31/42/102 32/43/107 44/59/108 39/58/103 -s 4 -f 32/43/81 38/51/25 43/56/109 44/59/110 -s off -f 39/55/111 40/52/112 46/61/113 45/60/114 -s 9 -f 40/52/98 41/53/97 47/62/115 46/61/116 -s 3 -f 41/53/100 42/54/99 48/63/117 47/62/118 -s 10 -f 42/54/104 39/55/103 45/60/119 48/63/120 -s 11 -f 5/7/121 6/8/122 50/65/123 49/64/124 -f 6/8/122 7/10/125 51/66/126 50/65/123 -f 7/10/125 8/12/127 52/67/128 51/66/126 -f 8/12/127 10/19/129 54/69/130 52/67/128 -f 10/19/129 9/13/131 53/68/132 54/69/130 -s 12 -f 49/64/133 50/65/134 56/71/135 55/70/136 -s 13 -f 50/65/137 51/66/138 57/72/139 56/71/140 -s 14 -f 51/66/141 52/67/142 58/73/143 57/72/144 -f 52/67/142 54/69/145 60/75/146 58/73/143 -s 15 -f 54/69/147 53/68/148 59/74/149 60/75/150 -s 12 -f 55/70/136 56/71/135 124/137/151 125/138/152 -s 13 -f 56/71/140 57/72/139 129/142/153 124/137/154 -s 14 -f 57/72/144 58/73/143 128/141/155 129/142/156 -s 16 -f 146/159/157 147/160/158 148/161/159 149/162/160 -s 15 -f 60/75/150 59/74/149 126/139/161 127/140/162 -s 12 -f 61/76/163 62/77/164 68/83/165 67/82/166 -s 13 -f 62/77/167 63/78/168 69/84/169 68/83/170 -s 14 -f 63/78/171 64/79/172 70/85/173 69/84/174 -f 64/79/172 66/81/175 72/87/176 70/85/173 -s 15 -f 66/81/177 65/80/178 71/86/179 72/87/180 -s 17 -f 67/82/181 68/83/182 74/89/183 73/88/184 -s 18 -f 68/83/185 69/84/186 75/90/187 74/89/188 -s 19 -f 69/84/189 70/85/190 76/91/191 75/90/192 -s 20 -f 70/85/193 72/87/194 78/93/195 76/91/196 -s 21 -f 72/87/197 71/86/198 77/92/199 78/93/200 -s 17 -f 73/88/184 74/89/183 81/95/201 79/94/202 -s 18 -f 74/89/188 75/90/187 82/96/203 81/95/204 -s 19 -f 75/90/192 76/91/191 84/97/205 82/96/206 -s 20 -f 76/91/196 78/93/195 86/99/207 84/97/208 -s 21 -f 78/93/200 77/92/199 85/98/209 86/99/210 -s 22 -f 83/11/211 84/97/212 101/115/213 98/112/214 -s 20 -f 84/97/208 86/99/207 100/114/215 101/115/216 -s 21 -f 86/99/210 85/98/209 99/113/217 100/114/218 -s 23 -f 107/120/219 106/121/220 108/122/221 109/123/222 -s 21 -f 93/107/223 92/106/224 87/101/225 89/103/226 -s 20 -f 90/104/227 93/107/228 89/103/229 88/102/230 -s 24 -f 91/105/231 90/104/232 94/109/233 95/108/234 -s 20 -f 90/104/227 88/102/230 96/110/235 94/109/236 -s 5 -f 112/125/30 110/100/29 114/127/237 115/128/238 -s 21 -f 100/114/218 99/113/217 92/106/224 93/107/223 -s 20 -f 101/115/216 100/114/215 93/107/228 90/104/227 -s 22 -f 98/112/214 101/115/213 90/104/239 91/105/240 -s 17 -f 79/94/202 81/95/201 104/118/241 102/116/242 -s 18 -f 81/95/204 82/96/203 105/119/243 104/118/244 -s off -f 82/96/245 80/9/246 103/117/247 105/119/248 -s 24 -f 95/108/234 94/109/233 106/121/249 107/120/250 -s 23 -f 94/109/251 96/110/252 108/122/221 106/121/220 -s off -f 96/110/253 97/111/254 109/123/255 108/122/256 -s 25 -f 88/102/257 89/103/258 113/126/259 112/125/260 -s 21 -f 89/103/226 87/101/225 111/124/261 113/126/262 -s off -f 97/111/263 96/110/264 115/128/265 114/127/266 -s 25 -f 96/110/267 88/102/257 112/125/260 115/128/268 -s 26 -f 80/9/269 82/96/270 118/131/271 116/129/272 -f 82/96/270 84/97/273 119/132/274 118/131/271 -f 84/97/273 83/11/275 117/130/276 119/132/274 -s off -f 116/129/277 118/131/278 122/135/279 120/133/280 -f 118/131/281 119/132/282 123/136/283 122/135/284 -f 119/132/285 117/130/286 121/134/287 123/136/288 -s 12 -f 125/138/152 124/137/151 62/77/164 61/76/163 -s 15 -f 127/140/162 126/139/161 65/80/178 66/81/177 -s 14 -f 128/141/155 127/140/289 66/81/175 64/79/172 -f 129/142/156 128/141/155 64/79/172 63/78/171 -s 13 -f 124/137/154 129/142/153 63/78/168 62/77/167 -s 27 -f 58/73/290 60/75/291 131/144/292 130/143/293 -s 28 -f 60/75/294 127/140/295 132/145/296 131/144/297 -s 29 -f 127/140/298 128/141/299 133/146/300 132/145/301 -s 30 -f 128/141/302 58/73/303 130/143/304 133/146/305 -s 27 -f 130/143/293 131/144/292 135/148/306 134/147/307 -s 28 -f 131/144/297 132/145/296 136/149/308 135/148/309 -s 29 -f 132/145/301 133/146/300 137/150/310 136/149/311 -s 30 -f 133/146/305 130/143/304 134/147/312 137/150/313 -s 27 -f 134/147/307 135/148/306 139/152/314 138/151/315 -s off -f 135/148/316 136/149/317 140/153/318 139/152/319 -s 29 -f 136/149/311 137/150/310 141/154/320 140/153/321 -s off -f 137/150/322 134/147/323 138/151/324 141/154/325 -s 27 -f 138/151/315 139/152/314 143/156/326 142/155/327 -s off -f 139/152/328 140/153/329 144/157/330 143/156/331 -s 29 -f 140/153/321 141/154/320 145/158/332 144/157/333 -s off -f 141/154/334 138/151/335 142/155/336 145/158/337 -f 142/155/338 143/156/339 147/160/340 146/159/341 -s 31 -f 143/156/342 144/157/343 148/161/344 147/160/345 -s 32 -f 145/158/346 142/155/347 146/159/348 149/162/349 -s off -f 150/163/350 151/164/351 152/165/352 153/166/353 -s 32 -f 145/158/346 149/162/349 151/164/354 150/163/355 -s 16 -f 149/162/160 148/161/159 152/165/356 151/164/357 -s 31 -f 148/161/344 144/157/343 153/166/358 152/165/359 -s off -f 144/157/360 145/158/361 150/163/362 153/166/363 -s 33 -f 19/167/364 20/170/365 167/169/366 166/168/367 -f 20/170/365 23/172/368 168/171/369 167/169/366 -s 34 -f 3/173/370 34/176/371 174/175/372 156/174/373 -s off -f 102/177/374 103/180/375 221/179/376 220/178/377 -f 120/181/378 121/184/379 230/183/380 229/182/381 -s 35 -f 35/185/382 11/188/383 161/187/384 175/186/385 -s 36 -f 154/189/386 155/192/387 177/191/388 176/190/389 -f 155/192/387 156/174/390 174/193/391 177/191/388 -s 37 -f 110/194/392 111/197/393 225/196/394 224/195/395 -s off -f 176/198/396 175/186/397 161/187/398 154/199/399 -s 33 -f 166/200/367 169/203/400 25/202/401 19/201/364 -s 38 -f 154/189/402 162/205/403 163/204/404 155/192/405 -f 155/192/405 163/204/404 164/206/406 156/174/407 -f 156/174/407 164/206/406 15/207/408 3/173/409 -f 11/188/410 17/209/411 165/208/412 161/187/413 -f 161/187/413 165/208/412 162/210/403 154/199/402 -s 39 -f 162/205/414 166/168/415 167/169/416 163/204/417 -s off -f 163/204/418 167/169/419 168/171/420 164/206/421 -f 164/206/422 168/171/423 23/172/424 15/207/425 -f 17/209/426 25/202/427 169/203/428 165/208/429 -s 39 -f 165/208/430 169/203/431 166/200/415 162/210/414 -s 34 -f 28/211/432 5/214/433 157/213/434 170/212/435 -s 35 -f 9/215/436 29/218/437 171/217/438 160/216/439 -s off -f 159/219/440 160/216/441 171/217/442 172/220/443 -s 36 -f 173/221/444 158/224/445 159/223/446 172/222/447 -f 170/225/448 157/226/449 158/224/445 173/221/444 -s 34 -f 34/176/371 28/211/432 170/212/435 174/175/372 -s 35 -f 29/218/437 35/185/382 175/186/385 171/217/438 -s off -f 184/227/450 187/230/451 186/229/452 185/228/453 -f 182/231/454 183/234/455 178/233/456 179/232/457 -s 36 -f 174/193/391 170/225/448 173/221/444 177/191/388 -s 41 -f 176/198/458 179/236/459 180/235/460 175/186/461 -s 35 -f 175/186/385 180/235/462 181/237/463 171/217/438 -s 42 -f 171/217/464 181/237/465 178/238/466 172/220/467 -s 41 -f 177/191/468 182/231/469 179/232/459 176/190/458 -s 42 -f 172/222/467 178/233/466 183/234/470 173/221/471 -s 36 -f 173/221/444 183/234/472 182/231/473 177/191/388 -s off -f 178/238/474 184/227/475 185/228/476 179/236/477 -s 41 -f 179/236/459 185/228/478 186/229/479 180/235/460 -s 35 -f 180/235/462 186/229/480 187/230/481 181/237/463 -s 42 -f 181/237/465 187/230/482 184/227/483 178/238/466 -s 43 -f 5/214/484 49/240/485 188/239/486 157/213/487 -f 157/213/487 188/239/486 189/242/488 158/241/489 -f 158/241/489 189/242/488 190/243/490 159/219/491 -f 159/219/491 190/243/490 191/244/492 160/216/493 -f 160/216/493 191/244/492 53/245/494 9/215/495 -s 44 -f 49/240/496 55/247/497 192/246/498 188/239/499 -s 45 -f 188/239/500 192/246/501 193/248/502 189/242/503 -s 46 -f 189/242/504 193/248/505 194/249/506 190/243/507 -f 190/243/507 194/249/506 195/250/508 191/244/509 -s 47 -f 191/244/510 195/250/511 59/251/512 53/245/513 -s 44 -f 55/247/497 125/253/514 231/252/515 192/246/498 -s 45 -f 192/246/501 231/252/516 234/254/517 193/248/502 -s 46 -f 193/248/505 234/254/518 233/255/519 194/249/506 -s 48 -f 251/256/520 254/259/521 253/258/522 252/257/523 -s 47 -f 195/250/511 232/261/524 126/260/525 59/251/512 -s 44 -f 61/262/526 67/265/527 200/264/528 196/263/529 -s 45 -f 196/263/530 200/264/531 201/267/532 197/266/533 -s 46 -f 197/266/534 201/267/535 202/269/536 198/268/537 -f 198/268/537 202/269/536 203/271/538 199/270/539 -s 47 -f 199/270/540 203/271/541 71/273/542 65/272/543 -s 50 -f 67/265/544 73/275/545 204/274/546 200/264/547 -s 51 -f 200/264/548 204/274/549 205/276/550 201/267/551 -s 52 -f 201/267/552 205/276/553 206/277/554 202/269/555 -s 53 -f 202/269/556 206/277/557 207/278/558 203/271/559 -s 54 -f 203/271/560 207/278/561 77/279/562 71/273/563 -s 50 -f 73/275/545 79/281/564 208/280/565 204/274/546 -s 51 -f 204/274/549 208/280/566 209/282/567 205/276/550 -s 52 -f 205/276/553 209/282/568 210/283/569 206/277/554 -s 53 -f 206/277/557 210/283/570 211/284/571 207/278/558 -s 54 -f 207/278/561 211/284/572 85/285/573 77/279/562 -s 55 -f 83/286/574 98/288/575 219/287/576 210/283/577 -s 53 -f 210/283/570 219/287/578 218/289/579 211/284/571 -s 54 -f 211/284/572 218/289/580 99/290/581 85/285/573 -s 56 -f 107/291/582 109/294/583 223/293/584 222/292/585 -s 54 -f 215/295/586 213/298/587 87/297/588 92/296/589 -s 53 -f 214/299/590 212/300/591 213/298/592 215/295/593 -s 59 -f 91/301/594 95/303/595 216/302/596 214/299/597 -s 53 -f 214/299/590 216/302/598 217/304/599 212/300/591 -s 37 -f 224/195/395 226/306/600 114/305/601 110/194/392 -s 54 -f 218/289/580 215/295/586 92/296/589 99/290/581 -s 53 -f 219/287/578 214/299/590 215/295/593 218/289/579 -s 55 -f 98/288/575 91/301/602 214/299/603 219/287/576 -s 50 -f 79/281/564 102/177/604 220/178/605 208/280/565 -s 51 -f 208/280/566 220/178/606 221/179/607 209/282/567 -s off -f 209/282/608 221/179/609 103/180/610 80/307/611 -s 59 -f 95/303/595 107/291/612 222/292/613 216/302/596 -s 56 -f 216/302/614 222/292/585 223/293/584 217/304/615 -s off -f 217/304/616 223/293/617 109/294/618 97/308/619 -s 60 -f 212/300/620 224/195/621 225/196/622 213/298/623 -s 54 -f 213/298/587 225/196/624 111/197/625 87/297/588 -s off -f 97/308/626 114/305/627 226/306/628 217/304/629 -s 60 -f 217/304/630 226/306/631 224/195/621 212/300/620 -s 61 -f 80/307/632 116/310/633 227/309/634 209/282/635 -f 209/282/635 227/309/634 228/311/636 210/283/637 -f 210/283/637 228/311/636 117/312/638 83/286/639 -s off -f 116/310/640 120/181/641 229/182/642 227/309/643 -f 227/309/644 229/182/645 230/183/646 228/311/647 -f 228/311/648 230/183/649 121/184/650 117/312/651 -s 44 -f 125/253/514 61/262/526 196/263/529 231/252/515 -s 47 -f 232/261/524 199/270/540 65/272/543 126/260/525 -s 46 -f 233/255/519 198/268/537 199/270/539 232/261/652 -f 234/254/518 197/266/534 198/268/537 233/255/519 -s 45 -f 231/252/516 196/263/530 197/266/533 234/254/517 -s 62 -f 194/249/653 235/314/654 236/313/655 195/250/656 -s 63 -f 195/250/657 236/313/658 237/315/659 232/261/660 -s 64 -f 232/261/661 237/315/662 238/316/663 233/255/664 -s 65 -f 233/255/665 238/316/666 235/314/667 194/249/668 -s 62 -f 235/314/654 239/318/669 240/317/670 236/313/655 -s 63 -f 236/313/658 240/317/671 241/319/672 237/315/659 -s 64 -f 237/315/662 241/319/673 242/320/674 238/316/663 -s 65 -f 238/316/666 242/320/675 239/318/676 235/314/667 -s 62 -f 239/318/669 243/322/677 244/321/678 240/317/670 -s off -f 240/317/679 244/321/680 245/323/681 241/319/682 -s 64 -f 241/319/673 245/323/683 246/324/684 242/320/674 -s off -f 242/320/685 246/324/686 243/322/687 239/318/688 -s 62 -f 243/322/677 247/326/689 248/325/690 244/321/678 -s off -f 244/321/691 248/325/692 249/327/693 245/323/694 -s 64 -f 245/323/683 249/327/695 250/328/696 246/324/684 -s off -f 246/324/697 250/328/698 247/326/699 243/322/700 -f 247/326/701 251/256/702 252/257/703 248/325/704 -s 66 -f 248/325/705 252/257/706 253/258/707 249/327/708 -s 67 -f 250/328/709 254/259/710 251/256/711 247/326/712 -s off -f 255/329/713 258/332/714 257/331/715 256/330/716 -s 67 -f 250/328/709 255/329/717 256/330/718 254/259/710 -s 48 -f 254/259/521 256/330/719 257/331/720 253/258/522 -s 66 -f 253/258/707 257/331/721 258/332/722 249/327/708 -s off -f 249/327/723 258/332/724 255/329/725 250/328/726 -g default -v 3.207954 1.063910 -3.086161 -v 3.207954 1.057989 -2.876540 -v 2.675397 1.063910 -3.086161 -v 2.675397 1.069832 -2.876540 -v 3.207954 1.063910 -2.666919 -v 2.675397 1.063910 -2.666919 -v 2.142840 1.063910 -3.086161 -v 2.142840 1.057989 -2.876540 -v 2.142840 1.063910 -2.666919 -v 3.207954 0.761656 -2.876540 -v 3.207954 0.761656 -2.606796 -v 2.675397 0.761656 -2.606796 -v 2.142840 0.761656 -2.606796 -v 2.142840 0.761656 -2.876540 -v 2.142840 0.761656 -3.146283 -v 2.675397 0.761656 -3.146283 -v 3.207954 0.761656 -3.146283 -v 1.709229 0.761656 -2.606796 -v 1.709229 0.761656 -2.876540 -v 1.709228 1.063910 -2.666919 -v 1.709228 1.057989 -2.876540 -v 1.709228 0.761656 -3.146283 -v 1.709228 1.063910 -3.086161 -v 3.207954 0.393788 -2.876540 -v 3.207954 0.459402 -3.206405 -v 2.675397 0.459402 -3.206405 -v 3.207954 0.459402 -2.546674 -v 2.675397 0.459402 -2.546674 -v 2.142840 0.459402 -3.206405 -v 2.142840 0.393788 -2.876540 -v 2.142840 0.459402 -2.546674 -vt 0.500000 0.875000 -vt 0.437500 0.875000 -vt 0.437500 0.750000 -vt 0.500000 0.750000 -vt 0.562500 0.875000 -vt 0.562500 0.750000 -vt 0.437500 0.625000 -vt 0.500000 0.625000 -vt 0.562500 0.625000 -vt 0.500000 0.875000 -vt 0.437500 0.875000 -vt 0.437500 0.875000 -vt 0.500000 0.875000 -vt 0.437500 0.750000 -vt 0.437500 0.750000 -vt 0.562500 0.875000 -vt 0.562500 0.875000 -vt 0.562500 0.750000 -vt 0.562500 0.750000 -vt 0.437500 0.625000 -vt 0.437500 0.625000 -vt 0.500000 0.625000 -vt 0.500000 0.625000 -vt 0.562500 0.625000 -vt 0.562500 0.625000 -vt 0.500000 0.625000 -vt 0.562500 0.625000 -vt 0.562500 0.625000 -vt 0.500000 0.625000 -vt 0.437500 0.625000 -vt 0.437500 0.625000 -vn 0.011118 0.999938 0.000000 -vn 0.011118 0.999938 0.000000 -vn -0.000000 1.000000 0.000000 -vn 0.000000 1.000000 0.000000 -vn 0.011119 0.999938 0.000000 -vn 0.000000 1.000000 0.000000 -vn -0.005560 0.999885 0.014121 -vn -0.005560 0.999985 -0.000000 -vn -0.005560 0.999885 -0.014121 -vn 1.000000 -0.000000 -0.000000 -vn 1.000000 0.000000 -0.000001 -vn 1.000000 0.000000 -0.000001 -vn 1.000000 0.000000 -0.000000 -vn 0.000000 0.195092 -0.980785 -vn 0.000000 0.195092 -0.980785 -vn 0.000000 0.195090 -0.980785 -vn 0.000000 0.195090 -0.980785 -vn 1.000000 -0.000001 0.000000 -vn 1.000000 0.000000 0.000000 -vn 0.000000 0.195090 0.980785 -vn 0.000000 0.195090 0.980785 -vn 0.000000 0.195091 0.980785 -vn 0.000000 0.195091 0.980785 -vn 0.000000 0.195092 -0.980785 -vn 0.000000 0.195090 -0.980785 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn 0.000000 0.195090 0.980785 -vn 0.000000 0.195091 0.980785 -vn 1.000000 0.000001 -0.000000 -vn 1.000000 0.000001 -0.000000 -vn 0.000000 0.195092 0.980785 -vn 0.000000 0.195092 0.980785 -vn 0.000000 0.195092 0.980785 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000001 0.000000 -vn -1.000000 -0.000001 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn 0.000000 0.195089 -0.980786 -vn 0.000000 0.195089 -0.980786 -vn 0.000000 0.195089 -0.980786 -vn 1.000000 0.000000 -0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 0.195092 0.980785 -vn 0.000000 0.195092 0.980785 -vn 0.000000 1.000000 -0.000000 -vn 0.000000 0.999601 -0.028238 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 0.999601 0.028238 -vn 0.000000 0.195089 -0.980786 -vn 0.000000 0.195089 -0.980786 -s 1 -g Chassis Axel_Rear_Right -usemtl initialShadingGroup -f 260/333/727 259/334/728 261/335/729 262/336/730 -f 263/337/731 260/333/727 262/336/730 264/338/732 -f 262/336/730 261/335/729 265/339/733 266/340/734 -f 264/338/732 262/336/730 266/340/734 267/341/735 -s 2 -f 282/342/736 283/343/737 275/344/738 268/345/739 -s 3 -f 283/343/740 284/346/741 274/347/742 275/344/743 -s 2 -f 285/348/744 282/342/736 268/345/739 269/349/745 -s 4 -f 286/350/746 285/348/747 269/349/748 270/351/749 -s 3 -f 284/346/741 287/352/750 273/353/751 274/347/742 -s 5 -f 287/352/752 288/354/753 272/355/754 273/353/755 -f 288/354/753 289/356/756 271/357/757 272/355/754 -s 4 -f 289/356/758 286/350/746 270/351/749 271/357/759 -s 2 -f 269/349/745 268/345/739 260/333/760 263/337/761 -s 4 -f 270/351/749 269/349/748 263/337/762 264/338/763 -f 271/357/759 270/351/749 264/338/763 267/341/764 -s 6 -f 277/358/765 276/359/766 278/360/767 279/361/768 -f 280/362/769 277/358/765 279/361/768 281/363/770 -s 3 -f 274/347/742 273/353/751 265/339/771 261/335/772 -f 275/344/743 274/347/742 261/335/772 259/334/773 -s 2 -f 268/345/739 275/344/738 259/334/774 260/333/760 -s 7 -f 272/355/775 271/357/776 276/359/777 277/358/778 -s 4 -f 271/357/759 267/341/764 278/360/779 276/359/780 -s 1 -f 267/341/735 266/340/734 279/361/781 278/360/782 -s 7 -f 273/353/783 272/355/775 277/358/778 280/362/784 -s 1 -f 266/340/734 265/339/733 281/363/785 279/361/781 -s 3 -f 265/339/771 273/353/751 280/362/786 281/363/787 -g default -v -3.207954 1.063910 -3.086161 -v -3.207954 1.057989 -2.876540 -v -2.675397 1.063910 -3.086161 -v -2.675397 1.069832 -2.876540 -v -3.207954 1.063910 -2.666919 -v -2.675397 1.063910 -2.666919 -v -2.142840 1.063910 -3.086161 -v -2.142840 1.057989 -2.876540 -v -2.142840 1.063910 -2.666919 -v -3.207954 0.761656 -2.876540 -v -3.207954 0.761656 -2.606796 -v -2.675397 0.761656 -2.606796 -v -2.142840 0.761656 -2.606796 -v -2.142840 0.761656 -2.876540 -v -2.142840 0.761656 -3.146283 -v -2.675397 0.761656 -3.146283 -v -3.207954 0.761656 -3.146283 -v -1.709229 0.761656 -2.606796 -v -1.709229 0.761656 -2.876540 -v -1.709228 1.063910 -2.666919 -v -1.709228 1.057989 -2.876540 -v -1.709228 0.761656 -3.146283 -v -1.709228 1.063910 -3.086161 -v -3.207954 0.393788 -2.876540 -v -3.207954 0.459402 -3.206405 -v -2.675397 0.459402 -3.206405 -v -3.207954 0.459402 -2.546674 -v -2.675397 0.459402 -2.546674 -v -2.142840 0.459402 -3.206405 -v -2.142840 0.393788 -2.876540 -v -2.142840 0.459402 -2.546674 -vt 0.500000 0.875000 -vt 0.437500 0.875000 -vt 0.437500 0.750000 -vt 0.500000 0.750000 -vt 0.562500 0.875000 -vt 0.562500 0.750000 -vt 0.437500 0.625000 -vt 0.500000 0.625000 -vt 0.562500 0.625000 -vt 0.500000 0.875000 -vt 0.437500 0.875000 -vt 0.437500 0.875000 -vt 0.500000 0.875000 -vt 0.437500 0.750000 -vt 0.437500 0.750000 -vt 0.562500 0.875000 -vt 0.562500 0.875000 -vt 0.562500 0.750000 -vt 0.562500 0.750000 -vt 0.437500 0.625000 -vt 0.437500 0.625000 -vt 0.500000 0.625000 -vt 0.500000 0.625000 -vt 0.562500 0.625000 -vt 0.562500 0.625000 -vt 0.500000 0.625000 -vt 0.562500 0.625000 -vt 0.562500 0.625000 -vt 0.500000 0.625000 -vt 0.437500 0.625000 -vt 0.437500 0.625000 -vn -0.011118 0.999938 0.000000 -vn -0.000000 1.000000 0.000000 -vn 0.000000 1.000000 0.000000 -vn -0.011118 0.999938 0.000000 -vn -0.011119 0.999938 0.000000 -vn -0.000000 1.000000 0.000000 -vn 0.005560 0.999985 -0.000000 -vn 0.005560 0.999885 0.014121 -vn 0.005560 0.999885 -0.014121 -vn -1.000000 0.000000 -0.000000 -vn -1.000000 0.000000 -0.000000 -vn -1.000000 0.000000 -0.000001 -vn -1.000000 0.000000 -0.000001 -vn 0.000000 0.195092 -0.980785 -vn 0.000000 0.195090 -0.980785 -vn 0.000000 0.195090 -0.980785 -vn 0.000000 0.195092 -0.980785 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -0.000000 0.195090 0.980785 -vn -0.000000 0.195091 0.980785 -vn -0.000000 0.195091 0.980785 -vn -0.000000 0.195090 0.980785 -vn 0.000000 0.195090 -0.980785 -vn 0.000000 0.195092 -0.980785 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 0.000000 0.195090 0.980785 -vn 0.000000 0.195091 0.980785 -vn -1.000000 0.000001 -0.000000 -vn -1.000000 0.000000 -0.000000 -vn 0.000000 0.195092 0.980785 -vn 0.000000 0.195092 0.980785 -vn 0.000000 0.195092 0.980785 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000001 0.000000 -vn 1.000000 -0.000001 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 0.000000 0.195089 -0.980786 -vn 0.000000 0.195089 -0.980786 -vn 0.000000 0.195089 -0.980786 -vn -1.000000 0.000000 -0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 0.195092 0.980785 -vn 0.000000 0.195092 0.980785 -vn 0.000000 0.999601 -0.028238 -vn 0.000000 1.000000 -0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 -1.000000 0.000000 -vn 0.000000 0.999601 0.028238 -vn 0.000000 0.195089 -0.980786 -vn 0.000000 0.195089 -0.980786 -s 1 -g Chassis Axel_Rear_Right1 -usemtl initialShadingGroup -f 291/364/788 293/367/789 292/366/790 290/365/791 -f 294/368/792 295/369/793 293/367/789 291/364/788 -f 293/367/789 297/371/794 296/370/795 292/366/790 -f 295/369/793 298/372/796 297/371/794 293/367/789 -s 2 -f 313/373/797 299/376/798 306/375/799 314/374/800 -s 3 -f 314/374/801 306/375/802 305/378/803 315/377/804 -s 2 -f 316/379/805 300/380/806 299/376/798 313/373/797 -s 4 -f 317/381/807 301/382/808 300/380/809 316/379/810 -s 3 -f 315/377/804 305/378/803 304/384/811 318/383/812 -s 5 -f 318/383/813 304/384/814 303/386/815 319/385/816 -f 319/385/816 303/386/815 302/388/817 320/387/818 -s 4 -f 320/387/819 302/388/820 301/382/808 317/381/807 -s 2 -f 300/380/806 294/368/821 291/364/822 299/376/798 -s 4 -f 301/382/808 295/369/823 294/368/824 300/380/809 -f 302/388/820 298/372/825 295/369/823 301/382/808 -s 6 -f 308/389/826 310/392/827 309/391/828 307/390/829 -f 311/393/830 312/394/831 310/392/827 308/389/826 -s 3 -f 305/378/803 292/366/832 296/370/833 304/384/811 -f 306/375/802 290/365/834 292/366/832 305/378/803 -s 2 -f 299/376/798 291/364/822 290/365/835 306/375/799 -s 7 -f 303/386/836 308/389/837 307/390/838 302/388/839 -s 4 -f 302/388/820 307/390/840 309/391/841 298/372/825 -s 1 -f 298/372/796 309/391/842 310/392/843 297/371/794 -s 7 -f 304/384/844 311/393/845 308/389/837 303/386/836 -s 1 -f 297/371/794 310/392/843 312/394/846 296/370/795 -s 3 -f 296/370/833 312/394/847 311/393/848 304/384/811 diff --git a/models/LightCycle_Wheel_Front_Left.obj b/models/LightCycle_Wheel_Front_Left.obj deleted file mode 100644 index eeacb1c..0000000 --- a/models/LightCycle_Wheel_Front_Left.obj +++ /dev/null @@ -1,627 +0,0 @@ -# This file uses centimeters as units for non-parametric coordinates. - -mtllib LightCycle_Wheel_Front_Left.mtl -g default -v -0.713786 0.830582 0.000000 -v -0.713786 0.767357 -0.317850 -v -0.713786 0.587310 -0.587309 -v -0.713786 0.317850 -0.767357 -v -0.713786 -0.000000 -0.830581 -v -0.713786 -0.317850 -0.767357 -v -0.713786 -0.587310 -0.587309 -v -0.713786 -0.767357 -0.317849 -v -0.713786 -0.830581 0.000000 -v -0.713786 -0.767357 0.317850 -v -0.713786 -0.587309 0.587310 -v -0.713786 -0.317849 0.767357 -v -0.713786 0.000000 0.830582 -v -0.713786 0.317850 0.767357 -v -0.713786 0.587310 0.587309 -v -0.713786 0.767357 0.317849 -v -0.237929 0.830582 0.000000 -v -0.237929 0.767357 -0.317850 -v -0.237929 0.587310 -0.587309 -v -0.237929 0.317850 -0.767357 -v -0.237929 -0.000000 -0.830581 -v -0.237929 -0.317850 -0.767357 -v -0.237929 -0.587310 -0.587309 -v -0.237929 -0.767357 -0.317849 -v -0.237929 -0.830581 0.000000 -v -0.237929 -0.767357 0.317850 -v -0.237929 -0.587309 0.587310 -v -0.237929 -0.317849 0.767357 -v -0.237929 0.000000 0.830582 -v -0.237929 0.317850 0.767357 -v -0.237929 0.587310 0.587309 -v -0.237929 0.767357 0.317849 -v 0.237929 0.830581 0.000000 -v 0.237929 0.767357 -0.317850 -v 0.237929 0.587310 -0.587309 -v 0.237929 0.317850 -0.767357 -v 0.237929 -0.000000 -0.830581 -v 0.237929 -0.317850 -0.767357 -v 0.237929 -0.587310 -0.587309 -v 0.237929 -0.767357 -0.317849 -v 0.237929 -0.767357 0.317850 -v 0.237929 -0.587309 0.587310 -v 0.237929 -0.317849 0.767357 -v 0.237929 0.000000 0.830582 -v 0.237929 0.317850 0.767357 -v 0.237929 0.587310 0.587309 -v 0.237929 0.767357 0.317849 -v 0.713786 0.830581 0.000000 -v 0.713786 0.767357 -0.317850 -v 0.713786 0.587310 -0.587309 -v 0.713786 0.317850 -0.767357 -v 0.713786 -0.000000 -0.830581 -v 0.713786 -0.317850 -0.767357 -v 0.713786 -0.587310 -0.587309 -v 0.713786 -0.767357 -0.317849 -v 0.713786 -0.830581 0.000000 -v 0.713786 -0.767357 0.317850 -v 0.713786 -0.587309 0.587310 -v 0.713786 -0.317849 0.767357 -v 0.713786 0.000000 0.830582 -v 0.713786 0.317850 0.767357 -v 0.713786 0.587310 0.587309 -v 0.713786 0.767357 0.317849 -v 0.713786 1.107442 0.000000 -v 0.713786 1.023143 -0.423800 -v 0.713786 0.783080 -0.783080 -v 0.713786 0.423800 -1.023143 -v 0.713786 -0.000000 -1.107442 -v 0.713786 -0.423800 -1.023143 -v 0.713786 -0.783080 -0.783079 -v 0.713786 -1.023143 -0.423799 -v 0.713786 -1.107442 0.000000 -v 0.713786 -1.023143 0.423800 -v 0.713786 -0.783079 0.783080 -v 0.713786 -0.423799 1.023143 -v 0.713786 0.000001 1.107442 -v 0.713786 0.423800 1.023143 -v 0.713786 0.783080 0.783079 -v 0.713786 1.023143 0.423799 -v 0.259053 1.205764 0.000000 -v 0.259053 1.113980 -0.461426 -v 0.259053 0.852604 -0.852604 -v 0.259053 0.461426 -1.113981 -v 0.259053 -0.000000 -1.205764 -v 0.259053 -0.461426 -1.113980 -v 0.259053 -0.852604 -0.852603 -v 0.259053 -1.113981 -0.461425 -v 0.259053 -1.205764 0.000000 -v 0.259053 -1.113980 0.461427 -v 0.259053 -0.852604 0.852604 -v 0.259053 -0.461425 1.113981 -v 0.259053 0.000001 1.205764 -v 0.259053 0.461427 1.113980 -v 0.259053 0.852604 0.852603 -v 0.259053 1.113981 0.461426 -v -0.259053 1.205764 0.000000 -v -0.259053 1.113980 -0.461426 -v -0.259052 0.852604 -0.852604 -v -0.259052 0.461426 -1.113981 -v -0.259052 -0.000000 -1.205764 -v -0.259053 -0.461426 -1.113980 -v -0.259052 -0.852604 -0.852603 -v -0.259052 -1.113981 -0.461425 -v -0.259053 -1.205764 0.000000 -v -0.259052 -1.113980 0.461427 -v -0.259052 -0.852604 0.852604 -v -0.259052 -0.461425 1.113981 -v -0.259052 0.000001 1.205764 -v -0.259052 0.461427 1.113980 -v -0.259052 0.852604 0.852603 -v -0.259053 1.113981 0.461426 -v -0.713786 1.107442 0.000000 -v -0.713786 1.023143 -0.423800 -v -0.713786 0.783080 -0.783080 -v -0.713786 0.423800 -1.023143 -v -0.713786 -0.000000 -1.107442 -v -0.713786 -0.423800 -1.023143 -v -0.713786 -0.783080 -0.783079 -v -0.713786 -1.023143 -0.423799 -v -0.713786 -1.107442 0.000000 -v -0.713786 -1.023143 0.423800 -v -0.713786 -0.783079 0.783080 -v -0.713786 -0.423799 1.023143 -v -0.713786 0.000001 1.107442 -v -0.713786 0.423800 1.023143 -v -0.713786 0.783080 0.783079 -v -0.713786 1.023143 0.423799 -v 0.237929 -0.830581 0.000000 -vt 0.062500 1.000000 -vt 0.000000 1.000000 -vt 0.000000 0.875000 -vt 0.062500 0.875000 -vt 0.125000 1.000000 -vt 0.125000 0.875000 -vt 0.187500 1.000000 -vt 0.187500 0.875000 -vt 0.250000 1.000000 -vt 0.250000 0.875000 -vt 0.312500 1.000000 -vt 0.312500 0.875000 -vt 0.375000 1.000000 -vt 0.375000 0.875000 -vt 0.437500 1.000000 -vt 0.437500 0.875000 -vt 0.500000 1.000000 -vt 0.500000 0.875000 -vt 0.562500 1.000000 -vt 0.562500 0.875000 -vt 0.625000 1.000000 -vt 0.625000 0.875000 -vt 0.687500 1.000000 -vt 0.687500 0.875000 -vt 0.750000 1.000000 -vt 0.750000 0.875000 -vt 0.812500 1.000000 -vt 0.812500 0.875000 -vt 0.875000 1.000000 -vt 0.875000 0.875000 -vt 0.937500 1.000000 -vt 0.937500 0.875000 -vt 1.000000 1.000000 -vt 1.000000 0.875000 -vt 0.000000 0.750000 -vt 0.062500 0.750000 -vt 0.125000 0.750000 -vt 0.187500 0.750000 -vt 0.250000 0.750000 -vt 0.312500 0.750000 -vt 0.375000 0.750000 -vt 0.437500 0.750000 -vt 0.562500 0.750000 -vt 0.625000 0.750000 -vt 0.687500 0.750000 -vt 0.750000 0.750000 -vt 0.812500 0.750000 -vt 0.875000 0.750000 -vt 0.937500 0.750000 -vt 1.000000 0.750000 -vt 0.000000 0.625000 -vt 0.062500 0.625000 -vt 0.125000 0.625000 -vt 0.187500 0.625000 -vt 0.250000 0.625000 -vt 0.312500 0.625000 -vt 0.375000 0.625000 -vt 0.437500 0.625000 -vt 0.562500 0.625000 -vt 0.625000 0.625000 -vt 0.687500 0.625000 -vt 0.750000 0.625000 -vt 0.812500 0.625000 -vt 0.875000 0.625000 -vt 0.937500 0.625000 -vt 1.000000 0.625000 -vt 0.000000 0.500000 -vt 0.062500 0.500000 -vt 0.125000 0.500000 -vt 0.187500 0.500000 -vt 0.250000 0.500000 -vt 0.312500 0.500000 -vt 0.375000 0.500000 -vt 0.437500 0.500000 -vt 0.500000 0.625000 -vt 0.500000 0.500000 -vt 0.562500 0.500000 -vt 0.625000 0.500000 -vt 0.687500 0.500000 -vt 0.750000 0.500000 -vt 0.812500 0.500000 -vt 0.875000 0.500000 -vt 0.937500 0.500000 -vt 1.000000 0.500000 -vt 0.000000 0.375000 -vt 0.062500 0.375000 -vt 0.125000 0.375000 -vt 0.187500 0.375000 -vt 0.250000 0.375000 -vt 0.312500 0.375000 -vt 0.375000 0.375000 -vt 0.437500 0.375000 -vt 0.500000 0.375000 -vt 0.562500 0.375000 -vt 0.625000 0.375000 -vt 0.687500 0.375000 -vt 0.750000 0.375000 -vt 0.812500 0.375000 -vt 0.875000 0.375000 -vt 0.937500 0.375000 -vt 1.000000 0.375000 -vt 0.000000 0.250000 -vt 0.062500 0.250000 -vt 0.125000 0.250000 -vt 0.187500 0.250000 -vt 0.250000 0.250000 -vt 0.312500 0.250000 -vt 0.375000 0.250000 -vt 0.437500 0.250000 -vt 0.500000 0.250000 -vt 0.562500 0.250000 -vt 0.625000 0.250000 -vt 0.687500 0.250000 -vt 0.750000 0.250000 -vt 0.812500 0.250000 -vt 0.875000 0.250000 -vt 0.937500 0.250000 -vt 1.000000 0.250000 -vt 0.000000 0.125000 -vt 0.062500 0.125000 -vt 0.125000 0.125000 -vt 0.187500 0.125000 -vt 0.250000 0.125000 -vt 0.312500 0.125000 -vt 0.375000 0.125000 -vt 0.437500 0.125000 -vt 0.500000 0.125000 -vt 0.562500 0.125000 -vt 0.625000 0.125000 -vt 0.687500 0.125000 -vt 0.750000 0.125000 -vt 0.812500 0.125000 -vt 0.875000 0.125000 -vt 0.937500 0.125000 -vt 1.000000 0.125000 -vt 0.000000 0.000000 -vt 0.062500 0.000000 -vt 0.125000 0.000000 -vt 0.187500 0.000000 -vt 0.250000 0.000000 -vt 0.312500 0.000000 -vt 0.375000 0.000000 -vt 0.437500 0.000000 -vt 0.500000 0.000000 -vt 0.562500 0.000000 -vt 0.625000 0.000000 -vt 0.687500 0.000000 -vt 0.750000 0.000000 -vt 0.812500 0.000000 -vt 0.875000 0.000000 -vt 0.937500 0.000000 -vt 1.000000 0.000000 -vt 0.000000 0.000000 -vt 1.000000 0.000000 -vt 1.000000 1.000000 -vt 0.000000 1.000000 -vt 0.000000 0.000000 -vt 1.000000 0.000000 -vt 1.000000 1.000000 -vt 0.000000 1.000000 -vt 0.000000 0.000000 -vt 1.000000 0.000000 -vt 1.000000 1.000000 -vt 0.000000 1.000000 -vt 0.000000 0.000000 -vt 1.000000 0.000000 -vt 1.000000 1.000000 -vt 0.000000 1.000000 -vn 0.000000 -0.923879 0.382684 -vn -0.000000 -0.923879 0.382684 -vn -0.000000 -1.000000 -0.000000 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -0.707107 0.707107 -vn 0.000000 -0.707107 0.707107 -vn 0.000000 -0.382684 0.923880 -vn 0.000000 -0.382684 0.923879 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.382684 0.923879 -vn 0.000000 0.382684 0.923879 -vn 0.000000 0.707107 0.707107 -vn 0.000000 0.707107 0.707107 -vn 0.000000 0.923880 0.382683 -vn 0.000000 0.923880 0.382683 -vn 0.000000 1.000000 -0.000000 -vn 0.000000 1.000000 -0.000000 -vn 0.000000 0.923879 -0.382684 -vn 0.000000 0.923879 -0.382684 -vn 0.000000 0.707106 -0.707107 -vn 0.000000 0.707106 -0.707107 -vn 0.000000 0.382684 -0.923880 -vn 0.000000 0.382684 -0.923880 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 0.000000 -1.000000 -vn 0.000000 -0.382685 -0.923879 -vn 0.000000 -0.382685 -0.923879 -vn 0.000000 -0.707107 -0.707107 -vn 0.000000 -0.707107 -0.707107 -vn 0.000000 -0.923879 -0.382684 -vn -0.000000 -0.923879 -0.382684 -vn -0.000000 -0.923880 0.382684 -vn -0.000000 -1.000000 -0.000000 -vn 0.000000 -0.707107 0.707107 -vn 0.000000 -0.382684 0.923879 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.382684 0.923879 -vn 0.000000 0.707107 0.707107 -vn 0.000000 0.923880 0.382683 -vn 0.000000 0.707106 -0.707107 -vn 0.000000 0.923879 -0.382684 -vn 0.000000 0.382684 -0.923880 -vn 0.000000 -0.000000 -1.000000 -vn 0.000000 -0.382684 -0.923879 -vn 0.000000 -0.707107 -0.707107 -vn -0.000000 -0.923879 -0.382684 -vn 0.000000 -0.923879 0.382684 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -0.707107 0.707107 -vn 0.000000 -0.382684 0.923879 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.382684 0.923879 -vn 0.000000 0.707107 0.707107 -vn 0.000000 0.923880 0.382683 -vn 0.000000 0.707106 -0.707107 -vn 0.000000 0.923879 -0.382684 -vn 0.000000 0.382684 -0.923880 -vn 0.000000 -0.000000 -1.000000 -vn 0.000000 -0.382685 -0.923879 -vn 0.000000 -0.707107 -0.707107 -vn 0.000000 -0.923880 -0.382684 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 -0.000000 -0.000000 -vn 1.000000 -0.000000 -0.000000 -vn 1.000000 -0.000000 -0.000000 -vn 1.000000 -0.000000 -0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 0.211335 0.903013 -0.374040 -vn 0.106314 0.918644 -0.380515 -vn 0.106315 0.994333 -0.000000 -vn 0.211335 0.977414 -0.000000 -vn 0.211335 0.691136 -0.691136 -vn 0.106315 0.703099 -0.703099 -vn 0.211336 0.374040 -0.903013 -vn 0.106315 0.380515 -0.918644 -vn 0.211335 -0.000000 -0.977414 -vn 0.106315 -0.000000 -0.994333 -vn 0.211335 -0.374040 -0.903012 -vn 0.106315 -0.380515 -0.918643 -vn 0.211335 -0.691136 -0.691136 -vn 0.106315 -0.703099 -0.703099 -vn 0.211335 -0.903013 -0.374040 -vn 0.106315 -0.918644 -0.380514 -vn 0.211335 -0.977414 0.000000 -vn 0.106315 -0.994333 0.000000 -vn 0.211336 -0.903012 0.374040 -vn 0.106315 -0.918643 0.380515 -vn 0.211336 -0.691135 0.691136 -vn 0.106315 -0.703099 0.703100 -vn 0.211336 -0.374039 0.903013 -vn 0.106315 -0.380514 0.918644 -vn 0.211335 0.000001 0.977414 -vn 0.106315 0.000001 0.994333 -vn 0.211335 0.374041 0.903012 -vn 0.106314 0.380515 0.918643 -vn 0.211335 0.691136 0.691135 -vn 0.106315 0.703100 0.703099 -vn 0.211336 0.903012 0.374040 -vn 0.106315 0.918644 0.380515 -vn -0.106314 0.918643 -0.380515 -vn -0.106315 0.994333 -0.000000 -vn -0.106314 0.703100 -0.703099 -vn -0.106315 0.380515 -0.918644 -vn -0.106315 -0.000000 -0.994333 -vn -0.106315 -0.380515 -0.918643 -vn -0.106315 -0.703100 -0.703099 -vn -0.106315 -0.918644 -0.380514 -vn -0.106315 -0.994333 0.000000 -vn -0.106315 -0.918643 0.380515 -vn -0.106315 -0.703099 0.703099 -vn -0.106315 -0.380514 0.918644 -vn -0.106315 0.000001 0.994333 -vn -0.106314 0.380515 0.918643 -vn -0.106314 0.703099 0.703099 -vn -0.106315 0.918644 0.380515 -vn -0.211335 0.903013 -0.374040 -vn -0.211335 0.977414 -0.000000 -vn -0.211335 0.691136 -0.691136 -vn -0.211335 0.374040 -0.903012 -vn -0.211335 -0.000000 -0.977414 -vn -0.211335 -0.374040 -0.903012 -vn -0.211335 -0.691136 -0.691136 -vn -0.211335 -0.903013 -0.374040 -vn -0.211335 -0.977414 0.000000 -vn -0.211336 -0.903012 0.374040 -vn -0.211336 -0.691136 0.691136 -vn -0.211336 -0.374039 0.903013 -vn -0.211336 0.000001 0.977414 -vn -0.211335 0.374041 0.903012 -vn -0.211335 0.691136 0.691136 -vn -0.211336 0.903012 0.374040 -vn -1.000000 -0.000001 0.000000 -vn -1.000000 -0.000001 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 0.000001 0.000000 -vn -1.000000 0.000001 0.000000 -vn -1.000000 0.000001 0.000000 -vn -1.000000 0.000001 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000001 0.000000 -vn -1.000000 0.000001 0.000000 -vn 0.000000 1.000000 -0.000000 -vn 0.000000 1.000000 -0.000000 -s 1 -g Wheel_Front_Left -usemtl initialShadingGroup -f 2/1/1 18/4/2 17/3/3 1/2/4 -f 3/5/5 19/6/6 18/4/2 2/1/1 -f 4/7/7 20/8/8 19/6/6 3/5/5 -f 5/9/9 21/10/10 20/8/8 4/7/7 -f 6/11/11 22/12/12 21/10/10 5/9/9 -f 7/13/13 23/14/14 22/12/12 6/11/11 -f 8/15/15 24/16/16 23/14/14 7/13/13 -f 9/17/17 25/18/18 24/16/16 8/15/15 -f 10/19/19 26/20/20 25/18/18 9/17/17 -f 11/21/21 27/22/22 26/20/20 10/19/19 -f 12/23/23 28/24/24 27/22/22 11/21/21 -f 13/25/25 29/26/26 28/24/24 12/23/23 -f 14/27/27 30/28/28 29/26/26 13/25/25 -f 15/29/29 31/30/30 30/28/28 14/27/27 -f 16/31/31 32/32/32 31/30/30 15/29/29 -f 1/33/4 17/34/3 32/32/32 16/31/31 -f 18/4/2 34/36/33 33/35/34 17/3/3 -f 19/6/6 35/37/35 34/36/33 18/4/2 -f 20/8/8 36/38/36 35/37/35 19/6/6 -f 21/10/10 37/39/37 36/38/36 20/8/8 -f 22/12/12 38/40/38 37/39/37 21/10/10 -f 23/14/14 39/41/39 38/40/38 22/12/12 -f 24/16/16 40/42/40 39/41/39 23/14/14 -f 27/22/22 42/44/41 41/43/42 26/20/20 -f 28/24/24 43/45/43 42/44/41 27/22/22 -f 29/26/26 44/46/44 43/45/43 28/24/24 -f 30/28/28 45/47/45 44/46/44 29/26/26 -f 31/30/30 46/48/46 45/47/45 30/28/28 -f 32/32/32 47/49/47 46/48/46 31/30/30 -f 17/34/3 33/50/34 47/49/47 32/32/32 -f 34/36/33 49/52/48 48/51/49 33/35/34 -f 35/37/35 50/53/50 49/52/48 34/36/33 -f 36/38/36 51/54/51 50/53/50 35/37/35 -f 37/39/37 52/55/52 51/54/51 36/38/36 -f 38/40/38 53/56/53 52/55/52 37/39/37 -f 39/41/39 54/57/54 53/56/53 38/40/38 -f 40/42/40 55/58/55 54/57/54 39/41/39 -f 42/44/41 58/60/56 57/59/57 41/43/42 -f 43/45/43 59/61/58 58/60/56 42/44/41 -f 44/46/44 60/62/59 59/61/58 43/45/43 -f 45/47/45 61/63/60 60/62/59 44/46/44 -f 46/48/46 62/64/61 61/63/60 45/47/45 -f 47/49/47 63/65/62 62/64/61 46/48/46 -f 33/50/34 48/66/49 63/65/62 47/49/47 -s 2 -f 49/52/63 65/68/64 64/67/65 48/51/66 -f 50/53/67 66/69/68 65/68/64 49/52/63 -f 51/54/69 67/70/70 66/69/68 50/53/67 -f 52/55/71 68/71/72 67/70/70 51/54/69 -f 53/56/73 69/72/74 68/71/72 52/55/71 -f 54/57/75 70/73/76 69/72/74 53/56/73 -f 55/58/77 71/74/78 70/73/76 54/57/75 -f 56/75/79 72/76/80 71/74/78 55/58/77 -f 57/59/81 73/77/82 72/76/80 56/75/79 -f 58/60/83 74/78/84 73/77/82 57/59/81 -f 59/61/85 75/79/86 74/78/84 58/60/83 -f 60/62/87 76/80/88 75/79/86 59/61/85 -f 61/63/89 77/81/90 76/80/88 60/62/87 -f 62/64/91 78/82/92 77/81/90 61/63/89 -f 63/65/93 79/83/94 78/82/92 62/64/91 -f 48/66/66 64/84/65 79/83/94 63/65/93 -s 3 -f 65/68/95 81/86/96 80/85/97 64/67/98 -f 66/69/99 82/87/100 81/86/96 65/68/95 -f 67/70/101 83/88/102 82/87/100 66/69/99 -f 68/71/103 84/89/104 83/88/102 67/70/101 -f 69/72/105 85/90/106 84/89/104 68/71/103 -f 70/73/107 86/91/108 85/90/106 69/72/105 -f 71/74/109 87/92/110 86/91/108 70/73/107 -f 72/76/111 88/93/112 87/92/110 71/74/109 -f 73/77/113 89/94/114 88/93/112 72/76/111 -f 74/78/115 90/95/116 89/94/114 73/77/113 -f 75/79/117 91/96/118 90/95/116 74/78/115 -f 76/80/119 92/97/120 91/96/118 75/79/117 -f 77/81/121 93/98/122 92/97/120 76/80/119 -f 78/82/123 94/99/124 93/98/122 77/81/121 -f 79/83/125 95/100/126 94/99/124 78/82/123 -f 64/84/98 80/101/97 95/100/126 79/83/125 -f 81/86/96 97/103/127 96/102/128 80/85/97 -f 82/87/100 98/104/129 97/103/127 81/86/96 -f 83/88/102 99/105/130 98/104/129 82/87/100 -f 84/89/104 100/106/131 99/105/130 83/88/102 -f 85/90/106 101/107/132 100/106/131 84/89/104 -f 86/91/108 102/108/133 101/107/132 85/90/106 -f 87/92/110 103/109/134 102/108/133 86/91/108 -f 88/93/112 104/110/135 103/109/134 87/92/110 -f 89/94/114 105/111/136 104/110/135 88/93/112 -f 90/95/116 106/112/137 105/111/136 89/94/114 -f 91/96/118 107/113/138 106/112/137 90/95/116 -f 92/97/120 108/114/139 107/113/138 91/96/118 -f 93/98/122 109/115/140 108/114/139 92/97/120 -f 94/99/124 110/116/141 109/115/140 93/98/122 -f 95/100/126 111/117/142 110/116/141 94/99/124 -f 80/101/97 96/118/128 111/117/142 95/100/126 -f 97/103/127 113/120/143 112/119/144 96/102/128 -f 98/104/129 114/121/145 113/120/143 97/103/127 -f 99/105/130 115/122/146 114/121/145 98/104/129 -f 100/106/131 116/123/147 115/122/146 99/105/130 -f 101/107/132 117/124/148 116/123/147 100/106/131 -f 102/108/133 118/125/149 117/124/148 101/107/132 -f 103/109/134 119/126/150 118/125/149 102/108/133 -f 104/110/135 120/127/151 119/126/150 103/109/134 -f 105/111/136 121/128/152 120/127/151 104/110/135 -f 106/112/137 122/129/153 121/128/152 105/111/136 -f 107/113/138 123/130/154 122/129/153 106/112/137 -f 108/114/139 124/131/155 123/130/154 107/113/138 -f 109/115/140 125/132/156 124/131/155 108/114/139 -f 110/116/141 126/133/157 125/132/156 109/115/140 -f 111/117/142 127/134/158 126/133/157 110/116/141 -f 96/118/128 112/135/144 127/134/158 111/117/142 -s 4 -f 113/120/159 2/137/160 1/136/161 112/119/162 -f 114/121/163 3/138/164 2/137/160 113/120/159 -f 115/122/165 4/139/166 3/138/164 114/121/163 -f 116/123/167 5/140/168 4/139/166 115/122/165 -f 117/124/169 6/141/170 5/140/168 116/123/167 -f 118/125/171 7/142/172 6/141/170 117/124/169 -f 119/126/173 8/143/174 7/142/172 118/125/171 -f 120/127/175 9/144/176 8/143/174 119/126/173 -f 121/128/177 10/145/178 9/144/176 120/127/175 -f 122/129/179 11/146/180 10/145/178 121/128/177 -f 123/130/181 12/147/182 11/146/180 122/129/179 -f 124/131/183 13/148/184 12/147/182 123/130/181 -f 125/132/185 14/149/186 13/148/184 124/131/183 -f 126/133/187 15/150/188 14/149/186 125/132/185 -f 127/134/189 16/151/190 15/150/188 126/133/187 -f 112/135/162 1/152/161 16/151/190 127/134/189 -s 1 -f 25/153/18 128/156/191 40/155/40 24/154/16 -f 26/157/20 41/160/42 128/159/191 25/158/18 -f 128/161/191 56/164/192 55/163/55 40/162/40 -f 41/165/42 57/168/57 56/167/192 128/166/191 diff --git a/models/LightCycle_Wheel_Front_Right.obj b/models/LightCycle_Wheel_Front_Right.obj deleted file mode 100644 index 3816108..0000000 --- a/models/LightCycle_Wheel_Front_Right.obj +++ /dev/null @@ -1,627 +0,0 @@ -# This file uses centimeters as units for non-parametric coordinates. - -mtllib LightCycle_Wheel_Front_Right.mtl -g default -v 0.713786 0.830582 0.000000 -v 0.713786 0.767357 -0.317850 -v 0.713786 0.587310 -0.587309 -v 0.713786 0.317850 -0.767357 -v 0.713786 -0.000000 -0.830581 -v 0.713786 -0.317850 -0.767357 -v 0.713786 -0.587310 -0.587309 -v 0.713786 -0.767357 -0.317849 -v 0.713786 -0.830581 0.000000 -v 0.713786 -0.767357 0.317850 -v 0.713786 -0.587309 0.587310 -v 0.713786 -0.317849 0.767357 -v 0.713786 0.000000 0.830582 -v 0.713786 0.317850 0.767357 -v 0.713786 0.587310 0.587309 -v 0.713786 0.767357 0.317849 -v 0.237929 0.830582 0.000000 -v 0.237929 0.767357 -0.317850 -v 0.237929 0.587310 -0.587309 -v 0.237929 0.317850 -0.767357 -v 0.237929 -0.000000 -0.830581 -v 0.237929 -0.317850 -0.767357 -v 0.237929 -0.587310 -0.587309 -v 0.237929 -0.767357 -0.317849 -v 0.237929 -0.830581 0.000000 -v 0.237929 -0.767357 0.317850 -v 0.237929 -0.587309 0.587310 -v 0.237929 -0.317849 0.767357 -v 0.237929 0.000000 0.830582 -v 0.237929 0.317850 0.767357 -v 0.237929 0.587310 0.587309 -v 0.237929 0.767357 0.317849 -v -0.237929 0.830581 0.000000 -v -0.237929 0.767357 -0.317850 -v -0.237929 0.587310 -0.587309 -v -0.237929 0.317850 -0.767357 -v -0.237929 -0.000000 -0.830581 -v -0.237929 -0.317850 -0.767357 -v -0.237929 -0.587310 -0.587309 -v -0.237929 -0.767357 -0.317849 -v -0.237929 -0.767357 0.317850 -v -0.237929 -0.587309 0.587310 -v -0.237929 -0.317849 0.767357 -v -0.237929 0.000000 0.830582 -v -0.237929 0.317850 0.767357 -v -0.237929 0.587310 0.587309 -v -0.237929 0.767357 0.317849 -v -0.713786 0.830581 0.000000 -v -0.713786 0.767357 -0.317850 -v -0.713786 0.587310 -0.587309 -v -0.713786 0.317850 -0.767357 -v -0.713786 -0.000000 -0.830581 -v -0.713786 -0.317850 -0.767357 -v -0.713786 -0.587310 -0.587309 -v -0.713786 -0.767357 -0.317849 -v -0.713786 -0.830581 0.000000 -v -0.713786 -0.767357 0.317850 -v -0.713786 -0.587309 0.587310 -v -0.713786 -0.317849 0.767357 -v -0.713786 0.000000 0.830582 -v -0.713786 0.317850 0.767357 -v -0.713786 0.587310 0.587309 -v -0.713786 0.767357 0.317849 -v -0.713786 1.107442 0.000000 -v -0.713786 1.023143 -0.423800 -v -0.713786 0.783080 -0.783080 -v -0.713786 0.423800 -1.023143 -v -0.713786 -0.000000 -1.107442 -v -0.713786 -0.423800 -1.023143 -v -0.713786 -0.783080 -0.783079 -v -0.713786 -1.023143 -0.423799 -v -0.713786 -1.107442 0.000000 -v -0.713786 -1.023143 0.423800 -v -0.713786 -0.783079 0.783080 -v -0.713786 -0.423799 1.023143 -v -0.713786 0.000001 1.107442 -v -0.713786 0.423800 1.023143 -v -0.713786 0.783080 0.783079 -v -0.713786 1.023143 0.423799 -v -0.259053 1.205764 0.000000 -v -0.259053 1.113980 -0.461426 -v -0.259053 0.852604 -0.852604 -v -0.259053 0.461426 -1.113981 -v -0.259053 -0.000000 -1.205764 -v -0.259053 -0.461426 -1.113980 -v -0.259053 -0.852604 -0.852603 -v -0.259053 -1.113981 -0.461425 -v -0.259053 -1.205764 0.000000 -v -0.259053 -1.113980 0.461427 -v -0.259053 -0.852604 0.852604 -v -0.259053 -0.461425 1.113981 -v -0.259053 0.000001 1.205764 -v -0.259053 0.461427 1.113980 -v -0.259053 0.852604 0.852603 -v -0.259053 1.113981 0.461426 -v 0.259053 1.205764 0.000000 -v 0.259053 1.113980 -0.461426 -v 0.259052 0.852604 -0.852604 -v 0.259052 0.461426 -1.113981 -v 0.259052 -0.000000 -1.205764 -v 0.259053 -0.461426 -1.113980 -v 0.259052 -0.852604 -0.852603 -v 0.259052 -1.113981 -0.461425 -v 0.259053 -1.205764 0.000000 -v 0.259052 -1.113980 0.461427 -v 0.259052 -0.852604 0.852604 -v 0.259052 -0.461425 1.113981 -v 0.259052 0.000001 1.205764 -v 0.259052 0.461427 1.113980 -v 0.259052 0.852604 0.852603 -v 0.259053 1.113981 0.461426 -v 0.713786 1.107442 0.000000 -v 0.713786 1.023143 -0.423800 -v 0.713786 0.783080 -0.783080 -v 0.713786 0.423800 -1.023143 -v 0.713786 -0.000000 -1.107442 -v 0.713786 -0.423800 -1.023143 -v 0.713786 -0.783080 -0.783079 -v 0.713786 -1.023143 -0.423799 -v 0.713786 -1.107442 0.000000 -v 0.713786 -1.023143 0.423800 -v 0.713786 -0.783079 0.783080 -v 0.713786 -0.423799 1.023143 -v 0.713786 0.000001 1.107442 -v 0.713786 0.423800 1.023143 -v 0.713786 0.783080 0.783079 -v 0.713786 1.023143 0.423799 -v -0.237929 -0.830581 0.000000 -vt 0.062500 1.000000 -vt 0.000000 1.000000 -vt 0.000000 0.875000 -vt 0.062500 0.875000 -vt 0.125000 1.000000 -vt 0.125000 0.875000 -vt 0.187500 1.000000 -vt 0.187500 0.875000 -vt 0.250000 1.000000 -vt 0.250000 0.875000 -vt 0.312500 1.000000 -vt 0.312500 0.875000 -vt 0.375000 1.000000 -vt 0.375000 0.875000 -vt 0.437500 1.000000 -vt 0.437500 0.875000 -vt 0.500000 1.000000 -vt 0.500000 0.875000 -vt 0.562500 1.000000 -vt 0.562500 0.875000 -vt 0.625000 1.000000 -vt 0.625000 0.875000 -vt 0.687500 1.000000 -vt 0.687500 0.875000 -vt 0.750000 1.000000 -vt 0.750000 0.875000 -vt 0.812500 1.000000 -vt 0.812500 0.875000 -vt 0.875000 1.000000 -vt 0.875000 0.875000 -vt 0.937500 1.000000 -vt 0.937500 0.875000 -vt 1.000000 1.000000 -vt 1.000000 0.875000 -vt 0.000000 0.750000 -vt 0.062500 0.750000 -vt 0.125000 0.750000 -vt 0.187500 0.750000 -vt 0.250000 0.750000 -vt 0.312500 0.750000 -vt 0.375000 0.750000 -vt 0.437500 0.750000 -vt 0.562500 0.750000 -vt 0.625000 0.750000 -vt 0.687500 0.750000 -vt 0.750000 0.750000 -vt 0.812500 0.750000 -vt 0.875000 0.750000 -vt 0.937500 0.750000 -vt 1.000000 0.750000 -vt 0.000000 0.625000 -vt 0.062500 0.625000 -vt 0.125000 0.625000 -vt 0.187500 0.625000 -vt 0.250000 0.625000 -vt 0.312500 0.625000 -vt 0.375000 0.625000 -vt 0.437500 0.625000 -vt 0.562500 0.625000 -vt 0.625000 0.625000 -vt 0.687500 0.625000 -vt 0.750000 0.625000 -vt 0.812500 0.625000 -vt 0.875000 0.625000 -vt 0.937500 0.625000 -vt 1.000000 0.625000 -vt 0.000000 0.500000 -vt 0.062500 0.500000 -vt 0.125000 0.500000 -vt 0.187500 0.500000 -vt 0.250000 0.500000 -vt 0.312500 0.500000 -vt 0.375000 0.500000 -vt 0.437500 0.500000 -vt 0.500000 0.625000 -vt 0.500000 0.500000 -vt 0.562500 0.500000 -vt 0.625000 0.500000 -vt 0.687500 0.500000 -vt 0.750000 0.500000 -vt 0.812500 0.500000 -vt 0.875000 0.500000 -vt 0.937500 0.500000 -vt 1.000000 0.500000 -vt 0.000000 0.375000 -vt 0.062500 0.375000 -vt 0.125000 0.375000 -vt 0.187500 0.375000 -vt 0.250000 0.375000 -vt 0.312500 0.375000 -vt 0.375000 0.375000 -vt 0.437500 0.375000 -vt 0.500000 0.375000 -vt 0.562500 0.375000 -vt 0.625000 0.375000 -vt 0.687500 0.375000 -vt 0.750000 0.375000 -vt 0.812500 0.375000 -vt 0.875000 0.375000 -vt 0.937500 0.375000 -vt 1.000000 0.375000 -vt 0.000000 0.250000 -vt 0.062500 0.250000 -vt 0.125000 0.250000 -vt 0.187500 0.250000 -vt 0.250000 0.250000 -vt 0.312500 0.250000 -vt 0.375000 0.250000 -vt 0.437500 0.250000 -vt 0.500000 0.250000 -vt 0.562500 0.250000 -vt 0.625000 0.250000 -vt 0.687500 0.250000 -vt 0.750000 0.250000 -vt 0.812500 0.250000 -vt 0.875000 0.250000 -vt 0.937500 0.250000 -vt 1.000000 0.250000 -vt 0.000000 0.125000 -vt 0.062500 0.125000 -vt 0.125000 0.125000 -vt 0.187500 0.125000 -vt 0.250000 0.125000 -vt 0.312500 0.125000 -vt 0.375000 0.125000 -vt 0.437500 0.125000 -vt 0.500000 0.125000 -vt 0.562500 0.125000 -vt 0.625000 0.125000 -vt 0.687500 0.125000 -vt 0.750000 0.125000 -vt 0.812500 0.125000 -vt 0.875000 0.125000 -vt 0.937500 0.125000 -vt 1.000000 0.125000 -vt 0.000000 0.000000 -vt 0.062500 0.000000 -vt 0.125000 0.000000 -vt 0.187500 0.000000 -vt 0.250000 0.000000 -vt 0.312500 0.000000 -vt 0.375000 0.000000 -vt 0.437500 0.000000 -vt 0.500000 0.000000 -vt 0.562500 0.000000 -vt 0.625000 0.000000 -vt 0.687500 0.000000 -vt 0.750000 0.000000 -vt 0.812500 0.000000 -vt 0.875000 0.000000 -vt 0.937500 0.000000 -vt 1.000000 0.000000 -vt 0.000000 0.000000 -vt 1.000000 0.000000 -vt 1.000000 1.000000 -vt 0.000000 1.000000 -vt 0.000000 0.000000 -vt 1.000000 0.000000 -vt 1.000000 1.000000 -vt 0.000000 1.000000 -vt 0.000000 0.000000 -vt 1.000000 0.000000 -vt 1.000000 1.000000 -vt 0.000000 1.000000 -vt 0.000000 0.000000 -vt 1.000000 0.000000 -vt 1.000000 1.000000 -vt 0.000000 1.000000 -vn 0.000000 -0.923879 0.382684 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -0.923879 0.382684 -vn 0.000000 -0.707107 0.707107 -vn 0.000000 -0.707107 0.707107 -vn 0.000000 -0.382684 0.923880 -vn 0.000000 -0.382684 0.923879 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.382684 0.923879 -vn 0.000000 0.382684 0.923880 -vn 0.000000 0.707107 0.707107 -vn 0.000000 0.707107 0.707107 -vn 0.000000 0.923880 0.382683 -vn 0.000000 0.923880 0.382683 -vn 0.000000 1.000000 -0.000000 -vn -0.000000 1.000000 -0.000000 -vn 0.000000 0.923879 -0.382684 -vn 0.000000 0.923879 -0.382684 -vn 0.000000 0.707106 -0.707107 -vn -0.000000 0.707106 -0.707107 -vn 0.000000 0.382684 -0.923880 -vn -0.000000 0.382684 -0.923880 -vn -0.000000 0.000000 -1.000000 -vn -0.000000 0.000000 -1.000000 -vn -0.000000 -0.382684 -0.923879 -vn -0.000000 -0.382685 -0.923879 -vn 0.000000 -0.707107 -0.707107 -vn 0.000000 -0.707107 -0.707107 -vn 0.000000 -0.923879 -0.382684 -vn 0.000000 -0.923880 -0.382684 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -0.923879 0.382684 -vn 0.000000 -0.707107 0.707107 -vn 0.000000 -0.382684 0.923879 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.382684 0.923879 -vn 0.000000 0.707107 0.707107 -vn 0.000000 0.923880 0.382683 -vn 0.000000 0.923879 -0.382684 -vn -0.000000 0.707106 -0.707107 -vn -0.000000 0.382684 -0.923879 -vn -0.000000 -0.000000 -1.000000 -vn 0.000000 -0.382685 -0.923879 -vn 0.000000 -0.707107 -0.707107 -vn 0.000000 -0.923880 -0.382683 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -0.923880 0.382684 -vn 0.000000 -0.707107 0.707107 -vn 0.000000 -0.382684 0.923879 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.382684 0.923879 -vn 0.000000 0.707107 0.707107 -vn 0.000000 0.923880 0.382683 -vn 0.000000 0.923880 -0.382684 -vn 0.000000 0.707106 -0.707107 -vn -0.000000 0.382684 -0.923880 -vn -0.000000 -0.000000 -1.000000 -vn 0.000000 -0.382685 -0.923879 -vn 0.000000 -0.707107 -0.707107 -vn 0.000000 -0.923880 -0.382683 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 0.000000 -0.000000 -vn -1.000000 0.000000 -0.000000 -vn -1.000000 0.000000 -0.000000 -vn -1.000000 0.000000 -0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 -0.000000 -0.000000 -vn -1.000000 -0.000000 -0.000000 -vn -1.000000 -0.000000 -0.000000 -vn -1.000000 -0.000000 -0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -0.211335 0.903013 -0.374040 -vn -0.211335 0.977414 0.000000 -vn -0.106315 0.994333 -0.000000 -vn -0.106314 0.918643 -0.380515 -vn -0.211335 0.691136 -0.691136 -vn -0.106314 0.703099 -0.703099 -vn -0.211335 0.374040 -0.903013 -vn -0.106315 0.380514 -0.918644 -vn -0.211336 -0.000000 -0.977414 -vn -0.106315 -0.000000 -0.994333 -vn -0.211335 -0.374040 -0.903012 -vn -0.106315 -0.380515 -0.918643 -vn -0.211335 -0.691136 -0.691135 -vn -0.106315 -0.703100 -0.703099 -vn -0.211335 -0.903013 -0.374040 -vn -0.106315 -0.918644 -0.380514 -vn -0.211336 -0.977414 0.000000 -vn -0.106315 -0.994333 0.000000 -vn -0.211336 -0.903012 0.374040 -vn -0.106315 -0.918643 0.380515 -vn -0.211336 -0.691135 0.691136 -vn -0.106315 -0.703099 0.703100 -vn -0.211336 -0.374039 0.903013 -vn -0.106315 -0.380514 0.918644 -vn -0.211336 0.000001 0.977414 -vn -0.106315 0.000001 0.994333 -vn -0.211335 0.374041 0.903012 -vn -0.106314 0.380515 0.918643 -vn -0.211335 0.691136 0.691135 -vn -0.106315 0.703100 0.703099 -vn -0.211336 0.903013 0.374040 -vn -0.106315 0.918644 0.380515 -vn 0.106315 0.994333 -0.000000 -vn 0.106314 0.918644 -0.380515 -vn 0.106314 0.703099 -0.703099 -vn 0.106315 0.380515 -0.918644 -vn 0.106315 -0.000000 -0.994333 -vn 0.106315 -0.380515 -0.918643 -vn 0.106315 -0.703100 -0.703099 -vn 0.106315 -0.918644 -0.380514 -vn 0.106315 -0.994333 0.000000 -vn 0.106315 -0.918643 0.380515 -vn 0.106315 -0.703099 0.703100 -vn 0.106315 -0.380514 0.918644 -vn 0.106315 0.000001 0.994333 -vn 0.106314 0.380515 0.918643 -vn 0.106314 0.703100 0.703099 -vn 0.106315 0.918644 0.380515 -vn 0.211335 0.977414 0.000000 -vn 0.211335 0.903013 -0.374040 -vn 0.211335 0.691136 -0.691136 -vn 0.211335 0.374040 -0.903013 -vn 0.211335 -0.000000 -0.977414 -vn 0.211336 -0.374040 -0.903012 -vn 0.211335 -0.691136 -0.691135 -vn 0.211335 -0.903013 -0.374040 -vn 0.211336 -0.977414 0.000000 -vn 0.211336 -0.903012 0.374040 -vn 0.211336 -0.691136 0.691136 -vn 0.211336 -0.374039 0.903013 -vn 0.211335 0.000001 0.977414 -vn 0.211335 0.374041 0.903012 -vn 0.211335 0.691136 0.691135 -vn 0.211336 0.903013 0.374040 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 -0.000000 -vn 1.000000 0.000000 -0.000000 -vn 1.000000 0.000000 -0.000000 -vn 1.000000 0.000000 -0.000000 -vn 1.000000 0.000000 -0.000000 -vn 1.000000 0.000000 -0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn -0.000000 1.000000 -0.000000 -vn 0.000000 1.000000 -0.000000 -s 1 -g Wheel_Front_Right -usemtl initialShadingGroup -f 2/1/1 1/2/2 17/3/3 18/4/4 -f 3/5/5 2/1/1 18/4/4 19/6/6 -f 4/7/7 3/5/5 19/6/6 20/8/8 -f 5/9/9 4/7/7 20/8/8 21/10/10 -f 6/11/11 5/9/9 21/10/10 22/12/12 -f 7/13/13 6/11/11 22/12/12 23/14/14 -f 8/15/15 7/13/13 23/14/14 24/16/16 -f 9/17/17 8/15/15 24/16/16 25/18/18 -f 10/19/19 9/17/17 25/18/18 26/20/20 -f 11/21/21 10/19/19 26/20/20 27/22/22 -f 12/23/23 11/21/21 27/22/22 28/24/24 -f 13/25/25 12/23/23 28/24/24 29/26/26 -f 14/27/27 13/25/25 29/26/26 30/28/28 -f 15/29/29 14/27/27 30/28/28 31/30/30 -f 16/31/31 15/29/29 31/30/30 32/32/32 -f 1/33/2 16/31/31 32/32/32 17/34/3 -f 18/4/4 17/3/3 33/35/33 34/36/34 -f 19/6/6 18/4/4 34/36/34 35/37/35 -f 20/8/8 19/6/6 35/37/35 36/38/36 -f 21/10/10 20/8/8 36/38/36 37/39/37 -f 22/12/12 21/10/10 37/39/37 38/40/38 -f 23/14/14 22/12/12 38/40/38 39/41/39 -f 24/16/16 23/14/14 39/41/39 40/42/40 -f 27/22/22 26/20/20 41/43/41 42/44/42 -f 28/24/24 27/22/22 42/44/42 43/45/43 -f 29/26/26 28/24/24 43/45/43 44/46/44 -f 30/28/28 29/26/26 44/46/44 45/47/45 -f 31/30/30 30/28/28 45/47/45 46/48/46 -f 32/32/32 31/30/30 46/48/46 47/49/47 -f 17/34/3 32/32/32 47/49/47 33/50/33 -f 34/36/34 33/35/33 48/51/48 49/52/49 -f 35/37/35 34/36/34 49/52/49 50/53/50 -f 36/38/36 35/37/35 50/53/50 51/54/51 -f 37/39/37 36/38/36 51/54/51 52/55/52 -f 38/40/38 37/39/37 52/55/52 53/56/53 -f 39/41/39 38/40/38 53/56/53 54/57/54 -f 40/42/40 39/41/39 54/57/54 55/58/55 -f 42/44/42 41/43/41 57/59/56 58/60/57 -f 43/45/43 42/44/42 58/60/57 59/61/58 -f 44/46/44 43/45/43 59/61/58 60/62/59 -f 45/47/45 44/46/44 60/62/59 61/63/60 -f 46/48/46 45/47/45 61/63/60 62/64/61 -f 47/49/47 46/48/46 62/64/61 63/65/62 -f 33/50/33 47/49/47 63/65/62 48/66/48 -s 2 -f 49/52/63 48/51/64 64/67/65 65/68/66 -f 50/53/67 49/52/63 65/68/66 66/69/68 -f 51/54/69 50/53/67 66/69/68 67/70/70 -f 52/55/71 51/54/69 67/70/70 68/71/72 -f 53/56/73 52/55/71 68/71/72 69/72/74 -f 54/57/75 53/56/73 69/72/74 70/73/76 -f 55/58/77 54/57/75 70/73/76 71/74/78 -f 56/75/79 55/58/77 71/74/78 72/76/80 -f 57/59/81 56/75/79 72/76/80 73/77/82 -f 58/60/83 57/59/81 73/77/82 74/78/84 -f 59/61/85 58/60/83 74/78/84 75/79/86 -f 60/62/87 59/61/85 75/79/86 76/80/88 -f 61/63/89 60/62/87 76/80/88 77/81/90 -f 62/64/91 61/63/89 77/81/90 78/82/92 -f 63/65/93 62/64/91 78/82/92 79/83/94 -f 48/66/64 63/65/93 79/83/94 64/84/65 -s 3 -f 65/68/95 64/67/96 80/85/97 81/86/98 -f 66/69/99 65/68/95 81/86/98 82/87/100 -f 67/70/101 66/69/99 82/87/100 83/88/102 -f 68/71/103 67/70/101 83/88/102 84/89/104 -f 69/72/105 68/71/103 84/89/104 85/90/106 -f 70/73/107 69/72/105 85/90/106 86/91/108 -f 71/74/109 70/73/107 86/91/108 87/92/110 -f 72/76/111 71/74/109 87/92/110 88/93/112 -f 73/77/113 72/76/111 88/93/112 89/94/114 -f 74/78/115 73/77/113 89/94/114 90/95/116 -f 75/79/117 74/78/115 90/95/116 91/96/118 -f 76/80/119 75/79/117 91/96/118 92/97/120 -f 77/81/121 76/80/119 92/97/120 93/98/122 -f 78/82/123 77/81/121 93/98/122 94/99/124 -f 79/83/125 78/82/123 94/99/124 95/100/126 -f 64/84/96 79/83/125 95/100/126 80/101/97 -f 81/86/98 80/85/97 96/102/127 97/103/128 -f 82/87/100 81/86/98 97/103/128 98/104/129 -f 83/88/102 82/87/100 98/104/129 99/105/130 -f 84/89/104 83/88/102 99/105/130 100/106/131 -f 85/90/106 84/89/104 100/106/131 101/107/132 -f 86/91/108 85/90/106 101/107/132 102/108/133 -f 87/92/110 86/91/108 102/108/133 103/109/134 -f 88/93/112 87/92/110 103/109/134 104/110/135 -f 89/94/114 88/93/112 104/110/135 105/111/136 -f 90/95/116 89/94/114 105/111/136 106/112/137 -f 91/96/118 90/95/116 106/112/137 107/113/138 -f 92/97/120 91/96/118 107/113/138 108/114/139 -f 93/98/122 92/97/120 108/114/139 109/115/140 -f 94/99/124 93/98/122 109/115/140 110/116/141 -f 95/100/126 94/99/124 110/116/141 111/117/142 -f 80/101/97 95/100/126 111/117/142 96/118/127 -f 97/103/128 96/102/127 112/119/143 113/120/144 -f 98/104/129 97/103/128 113/120/144 114/121/145 -f 99/105/130 98/104/129 114/121/145 115/122/146 -f 100/106/131 99/105/130 115/122/146 116/123/147 -f 101/107/132 100/106/131 116/123/147 117/124/148 -f 102/108/133 101/107/132 117/124/148 118/125/149 -f 103/109/134 102/108/133 118/125/149 119/126/150 -f 104/110/135 103/109/134 119/126/150 120/127/151 -f 105/111/136 104/110/135 120/127/151 121/128/152 -f 106/112/137 105/111/136 121/128/152 122/129/153 -f 107/113/138 106/112/137 122/129/153 123/130/154 -f 108/114/139 107/113/138 123/130/154 124/131/155 -f 109/115/140 108/114/139 124/131/155 125/132/156 -f 110/116/141 109/115/140 125/132/156 126/133/157 -f 111/117/142 110/116/141 126/133/157 127/134/158 -f 96/118/127 111/117/142 127/134/158 112/135/143 -s 4 -f 113/120/159 112/119/160 1/136/161 2/137/162 -f 114/121/163 113/120/159 2/137/162 3/138/164 -f 115/122/165 114/121/163 3/138/164 4/139/166 -f 116/123/167 115/122/165 4/139/166 5/140/168 -f 117/124/169 116/123/167 5/140/168 6/141/170 -f 118/125/171 117/124/169 6/141/170 7/142/172 -f 119/126/173 118/125/171 7/142/172 8/143/174 -f 120/127/175 119/126/173 8/143/174 9/144/176 -f 121/128/177 120/127/175 9/144/176 10/145/178 -f 122/129/179 121/128/177 10/145/178 11/146/180 -f 123/130/181 122/129/179 11/146/180 12/147/182 -f 124/131/183 123/130/181 12/147/182 13/148/184 -f 125/132/185 124/131/183 13/148/184 14/149/186 -f 126/133/187 125/132/185 14/149/186 15/150/188 -f 127/134/189 126/133/187 15/150/188 16/151/190 -f 112/135/160 127/134/189 16/151/190 1/152/161 -s 1 -f 25/153/18 24/154/16 40/155/40 128/156/191 -f 26/157/20 25/158/18 128/159/191 41/160/41 -f 128/161/191 40/162/40 55/163/55 56/164/192 -f 41/165/41 128/166/191 56/167/192 57/168/56 diff --git a/models/LightCycle_Wheel_Rear_Left.obj b/models/LightCycle_Wheel_Rear_Left.obj deleted file mode 100644 index ac22268..0000000 --- a/models/LightCycle_Wheel_Rear_Left.obj +++ /dev/null @@ -1,627 +0,0 @@ -# This file uses centimeters as units for non-parametric coordinates. - -mtllib LightCycle_Wheel_Rear_Left.mtl -g default -v -0.798836 0.861980 0.000000 -v -0.798836 0.796366 -0.329865 -v -0.798836 0.609512 -0.609512 -v -0.798836 0.329866 -0.796366 -v -0.798836 -0.000000 -0.861980 -v -0.798836 -0.329865 -0.796366 -v -0.798836 -0.609512 -0.609511 -v -0.798836 -0.796366 -0.329865 -v -0.798836 -0.861980 0.000000 -v -0.798836 -0.796365 0.329866 -v -0.798836 -0.609512 0.609512 -v -0.798836 -0.329865 0.796365 -v -0.798836 0.000000 0.861980 -v -0.798836 0.329866 0.796365 -v -0.798836 0.609512 0.609512 -v -0.798836 0.796366 0.329865 -v -0.266278 0.861980 0.000000 -v -0.266278 0.796366 -0.329865 -v -0.266278 0.609512 -0.609512 -v -0.266278 0.329866 -0.796366 -v -0.266278 -0.000000 -0.861980 -v -0.266278 -0.329865 -0.796366 -v -0.266278 -0.609512 -0.609511 -v -0.266278 -0.796366 -0.329865 -v -0.266278 -0.861980 0.000000 -v -0.266278 -0.796365 0.329866 -v -0.266278 -0.609512 0.609512 -v -0.266278 -0.329865 0.796365 -v -0.266278 0.000000 0.861980 -v -0.266278 0.329866 0.796365 -v -0.266278 0.609512 0.609512 -v -0.266278 0.796366 0.329865 -v 0.266279 0.861980 0.000000 -v 0.266279 0.796366 -0.329865 -v 0.266279 0.609512 -0.609512 -v 0.266279 0.329866 -0.796366 -v 0.266279 -0.000000 -0.861980 -v 0.266279 -0.329865 -0.796366 -v 0.266279 -0.609512 -0.609511 -v 0.266279 -0.796366 -0.329865 -v 0.266279 -0.796365 0.329866 -v 0.266279 -0.609512 0.609512 -v 0.266279 -0.329865 0.796365 -v 0.266279 0.000000 0.861980 -v 0.266279 0.329866 0.796365 -v 0.266279 0.609512 0.609512 -v 0.266279 0.796366 0.329865 -v 0.798836 0.861980 0.000000 -v 0.798836 0.796366 -0.329865 -v 0.798836 0.609512 -0.609512 -v 0.798836 0.329866 -0.796366 -v 0.798836 0.000000 -0.861980 -v 0.798836 -0.329865 -0.796366 -v 0.798836 -0.609512 -0.609511 -v 0.798836 -0.796366 -0.329865 -v 0.798836 -0.861980 0.000000 -v 0.798836 -0.796365 0.329866 -v 0.798836 -0.609512 0.609512 -v 0.798836 -0.329865 0.796365 -v 0.798836 0.000000 0.861980 -v 0.798836 0.329866 0.796365 -v 0.798836 0.609512 0.609512 -v 0.798836 0.796366 0.329865 -v 0.798836 1.149307 0.000000 -v 0.798836 1.061821 -0.439821 -v 0.798836 0.812683 -0.812683 -v 0.798836 0.439821 -1.061821 -v 0.798836 0.000000 -1.149307 -v 0.798836 -0.439821 -1.061821 -v 0.798836 -0.812683 -0.812682 -v 0.798836 -1.061821 -0.439820 -v 0.798836 -1.149307 0.000001 -v 0.798836 -1.061821 0.439821 -v 0.798836 -0.812682 0.812683 -v 0.798836 -0.439820 1.061821 -v 0.798836 0.000001 1.149307 -v 0.798836 0.439821 1.061821 -v 0.798836 0.812683 0.812682 -v 0.798836 1.061821 0.439820 -v 0.289920 1.251346 0.000000 -v 0.289920 1.156093 -0.478869 -v 0.289920 0.884835 -0.884835 -v 0.289920 0.478869 -1.156093 -v 0.289920 -0.000000 -1.251345 -v 0.289920 -0.478870 -1.156092 -v 0.289920 -0.884835 -0.884835 -v 0.289920 -1.156093 -0.478869 -v 0.289920 -1.251346 0.000001 -v 0.289920 -1.156092 0.478870 -v 0.289920 -0.884835 0.884835 -v 0.289920 -0.478869 1.156093 -v 0.289920 0.000001 1.251345 -v 0.289920 0.478870 1.156092 -v 0.289920 0.884835 0.884835 -v 0.289920 1.156093 0.478869 -v -0.289919 1.251346 0.000000 -v -0.289919 1.156092 -0.478869 -v -0.289919 0.884835 -0.884835 -v -0.289919 0.478869 -1.156093 -v -0.289919 -0.000000 -1.251345 -v -0.289920 -0.478870 -1.156092 -v -0.289919 -0.884835 -0.884835 -v -0.289920 -1.156093 -0.478869 -v -0.289920 -1.251346 0.000001 -v -0.289919 -1.156092 0.478870 -v -0.289919 -0.884835 0.884835 -v -0.289919 -0.478869 1.156093 -v -0.289919 0.000001 1.251345 -v -0.289919 0.478870 1.156092 -v -0.289919 0.884835 0.884835 -v -0.289919 1.156093 0.478869 -v -0.798836 1.149307 0.000000 -v -0.798836 1.061821 -0.439821 -v -0.798836 0.812683 -0.812683 -v -0.798836 0.439821 -1.061821 -v -0.798836 -0.000000 -1.149307 -v -0.798836 -0.439821 -1.061821 -v -0.798836 -0.812683 -0.812682 -v -0.798836 -1.061821 -0.439820 -v -0.798836 -1.149307 0.000001 -v -0.798836 -1.061821 0.439821 -v -0.798836 -0.812682 0.812683 -v -0.798836 -0.439820 1.061821 -v -0.798836 0.000001 1.149307 -v -0.798836 0.439821 1.061821 -v -0.798836 0.812683 0.812682 -v -0.798836 1.061821 0.439820 -v 0.266279 -0.861980 0.000000 -vt 0.062500 1.000000 -vt 0.000000 1.000000 -vt 0.000000 0.875000 -vt 0.062500 0.875000 -vt 0.125000 1.000000 -vt 0.125000 0.875000 -vt 0.187500 1.000000 -vt 0.187500 0.875000 -vt 0.250000 1.000000 -vt 0.250000 0.875000 -vt 0.312500 1.000000 -vt 0.312500 0.875000 -vt 0.375000 1.000000 -vt 0.375000 0.875000 -vt 0.437500 1.000000 -vt 0.437500 0.875000 -vt 0.500000 1.000000 -vt 0.500000 0.875000 -vt 0.562500 1.000000 -vt 0.562500 0.875000 -vt 0.625000 1.000000 -vt 0.625000 0.875000 -vt 0.687500 1.000000 -vt 0.687500 0.875000 -vt 0.750000 1.000000 -vt 0.750000 0.875000 -vt 0.812500 1.000000 -vt 0.812500 0.875000 -vt 0.875000 1.000000 -vt 0.875000 0.875000 -vt 0.937500 1.000000 -vt 0.937500 0.875000 -vt 1.000000 1.000000 -vt 1.000000 0.875000 -vt 0.000000 0.750000 -vt 0.062500 0.750000 -vt 0.125000 0.750000 -vt 0.187500 0.750000 -vt 0.250000 0.750000 -vt 0.312500 0.750000 -vt 0.375000 0.750000 -vt 0.437500 0.750000 -vt 0.562500 0.750000 -vt 0.625000 0.750000 -vt 0.687500 0.750000 -vt 0.750000 0.750000 -vt 0.812500 0.750000 -vt 0.875000 0.750000 -vt 0.937500 0.750000 -vt 1.000000 0.750000 -vt 0.000000 0.625000 -vt 0.062500 0.625000 -vt 0.125000 0.625000 -vt 0.187500 0.625000 -vt 0.250000 0.625000 -vt 0.312500 0.625000 -vt 0.375000 0.625000 -vt 0.437500 0.625000 -vt 0.562500 0.625000 -vt 0.625000 0.625000 -vt 0.687500 0.625000 -vt 0.750000 0.625000 -vt 0.812500 0.625000 -vt 0.875000 0.625000 -vt 0.937500 0.625000 -vt 1.000000 0.625000 -vt 0.000000 0.500000 -vt 0.062500 0.500000 -vt 0.125000 0.500000 -vt 0.187500 0.500000 -vt 0.250000 0.500000 -vt 0.312500 0.500000 -vt 0.375000 0.500000 -vt 0.437500 0.500000 -vt 0.500000 0.625000 -vt 0.500000 0.500000 -vt 0.562500 0.500000 -vt 0.625000 0.500000 -vt 0.687500 0.500000 -vt 0.750000 0.500000 -vt 0.812500 0.500000 -vt 0.875000 0.500000 -vt 0.937500 0.500000 -vt 1.000000 0.500000 -vt 0.000000 0.375000 -vt 0.062500 0.375000 -vt 0.125000 0.375000 -vt 0.187500 0.375000 -vt 0.250000 0.375000 -vt 0.312500 0.375000 -vt 0.375000 0.375000 -vt 0.437500 0.375000 -vt 0.500000 0.375000 -vt 0.562500 0.375000 -vt 0.625000 0.375000 -vt 0.687500 0.375000 -vt 0.750000 0.375000 -vt 0.812500 0.375000 -vt 0.875000 0.375000 -vt 0.937500 0.375000 -vt 1.000000 0.375000 -vt 0.000000 0.250000 -vt 0.062500 0.250000 -vt 0.125000 0.250000 -vt 0.187500 0.250000 -vt 0.250000 0.250000 -vt 0.312500 0.250000 -vt 0.375000 0.250000 -vt 0.437500 0.250000 -vt 0.500000 0.250000 -vt 0.562500 0.250000 -vt 0.625000 0.250000 -vt 0.687500 0.250000 -vt 0.750000 0.250000 -vt 0.812500 0.250000 -vt 0.875000 0.250000 -vt 0.937500 0.250000 -vt 1.000000 0.250000 -vt 0.000000 0.125000 -vt 0.062500 0.125000 -vt 0.125000 0.125000 -vt 0.187500 0.125000 -vt 0.250000 0.125000 -vt 0.312500 0.125000 -vt 0.375000 0.125000 -vt 0.437500 0.125000 -vt 0.500000 0.125000 -vt 0.562500 0.125000 -vt 0.625000 0.125000 -vt 0.687500 0.125000 -vt 0.750000 0.125000 -vt 0.812500 0.125000 -vt 0.875000 0.125000 -vt 0.937500 0.125000 -vt 1.000000 0.125000 -vt 0.000000 0.000000 -vt 0.062500 0.000000 -vt 0.125000 0.000000 -vt 0.187500 0.000000 -vt 0.250000 0.000000 -vt 0.312500 0.000000 -vt 0.375000 0.000000 -vt 0.437500 0.000000 -vt 0.500000 0.000000 -vt 0.562500 0.000000 -vt 0.625000 0.000000 -vt 0.687500 0.000000 -vt 0.750000 0.000000 -vt 0.812500 0.000000 -vt 0.875000 0.000000 -vt 0.937500 0.000000 -vt 1.000000 0.000000 -vt 0.000000 0.000000 -vt 1.000000 0.000000 -vt 1.000000 1.000000 -vt 0.000000 1.000000 -vt 0.000000 0.000000 -vt 1.000000 0.000000 -vt 1.000000 1.000000 -vt 0.000000 1.000000 -vt 0.000000 0.000000 -vt 1.000000 0.000000 -vt 1.000000 1.000000 -vt 0.000000 1.000000 -vt 0.000000 0.000000 -vt 1.000000 0.000000 -vt 1.000000 1.000000 -vt 0.000000 1.000000 -vn 0.000000 -0.923880 0.382684 -vn -0.000000 -0.923880 0.382683 -vn -0.000000 -1.000000 -0.000000 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -0.707107 0.707107 -vn 0.000000 -0.707107 0.707107 -vn 0.000000 -0.382683 0.923880 -vn 0.000000 -0.382683 0.923880 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.382684 0.923879 -vn 0.000000 0.382684 0.923879 -vn 0.000000 0.707107 0.707107 -vn 0.000000 0.707107 0.707107 -vn 0.000000 0.923879 0.382684 -vn 0.000000 0.923879 0.382684 -vn 0.000000 1.000000 -0.000000 -vn 0.000000 1.000000 -0.000000 -vn 0.000000 0.923879 -0.382684 -vn 0.000000 0.923879 -0.382684 -vn 0.000000 0.707107 -0.707107 -vn 0.000000 0.707107 -0.707107 -vn 0.000000 0.382683 -0.923880 -vn 0.000000 0.382683 -0.923880 -vn 0.000000 -0.000000 -1.000000 -vn 0.000000 -0.000000 -1.000000 -vn 0.000000 -0.382684 -0.923879 -vn 0.000000 -0.382684 -0.923880 -vn 0.000000 -0.707107 -0.707107 -vn 0.000000 -0.707107 -0.707107 -vn 0.000000 -0.923880 -0.382684 -vn -0.000000 -0.923880 -0.382684 -vn -0.000000 -0.923880 0.382683 -vn -0.000000 -1.000000 -0.000000 -vn 0.000000 -0.707107 0.707107 -vn 0.000000 -0.382683 0.923880 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.382684 0.923879 -vn 0.000000 0.707107 0.707107 -vn 0.000000 0.923879 0.382684 -vn 0.000000 0.707107 -0.707107 -vn 0.000000 0.923879 -0.382684 -vn 0.000000 0.382683 -0.923880 -vn 0.000000 -0.000000 -1.000000 -vn 0.000000 -0.382684 -0.923880 -vn 0.000000 -0.707107 -0.707107 -vn -0.000000 -0.923880 -0.382684 -vn 0.000000 -0.923880 0.382683 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -0.707107 0.707107 -vn 0.000000 -0.382684 0.923880 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.382684 0.923879 -vn 0.000000 0.707107 0.707107 -vn 0.000000 0.923879 0.382684 -vn 0.000000 0.707107 -0.707107 -vn -0.000000 0.923879 -0.382684 -vn 0.000000 0.382684 -0.923880 -vn 0.000000 -0.000000 -1.000000 -vn 0.000000 -0.382684 -0.923880 -vn 0.000000 -0.707107 -0.707107 -vn 0.000000 -0.923880 -0.382684 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 0.196589 0.905851 -0.375216 -vn 0.098814 0.919358 -0.380811 -vn 0.098814 0.995106 -0.000000 -vn 0.196590 0.980486 -0.000000 -vn 0.196589 0.693308 -0.693308 -vn 0.098814 0.703646 -0.703646 -vn 0.196590 0.375215 -0.905851 -vn 0.098815 0.380810 -0.919358 -vn 0.196591 -0.000000 -0.980486 -vn 0.098815 -0.000000 -0.995106 -vn 0.196590 -0.375216 -0.905851 -vn 0.098814 -0.380811 -0.919358 -vn 0.196590 -0.693308 -0.693308 -vn 0.098814 -0.703646 -0.703646 -vn 0.196590 -0.905851 -0.375215 -vn 0.098814 -0.919358 -0.380810 -vn 0.196590 -0.980486 0.000000 -vn 0.098814 -0.995106 0.000000 -vn 0.196590 -0.905851 0.375216 -vn 0.098814 -0.919358 0.380811 -vn 0.196590 -0.693308 0.693308 -vn 0.098815 -0.703646 0.703646 -vn 0.196590 -0.375215 0.905851 -vn 0.098814 -0.380810 0.919358 -vn 0.196590 0.000001 0.980486 -vn 0.098814 0.000001 0.995106 -vn 0.196590 0.375216 0.905851 -vn 0.098814 0.380811 0.919358 -vn 0.196590 0.693308 0.693308 -vn 0.098815 0.703646 0.703646 -vn 0.196590 0.905851 0.375216 -vn 0.098815 0.919358 0.380810 -vn -0.098814 0.919358 -0.380811 -vn -0.098814 0.995106 -0.000000 -vn -0.098814 0.703646 -0.703646 -vn -0.098815 0.380810 -0.919358 -vn -0.098815 -0.000000 -0.995106 -vn -0.098814 -0.380811 -0.919358 -vn -0.098814 -0.703646 -0.703646 -vn -0.098814 -0.919358 -0.380810 -vn -0.098814 -0.995106 0.000000 -vn -0.098814 -0.919358 0.380811 -vn -0.098815 -0.703646 0.703646 -vn -0.098814 -0.380810 0.919358 -vn -0.098814 0.000001 0.995106 -vn -0.098814 0.380811 0.919358 -vn -0.098815 0.703646 0.703646 -vn -0.098814 0.919358 0.380810 -vn -0.196589 0.905851 -0.375216 -vn -0.196589 0.980486 -0.000000 -vn -0.196589 0.693308 -0.693308 -vn -0.196590 0.375216 -0.905851 -vn -0.196591 -0.000000 -0.980486 -vn -0.196590 -0.375216 -0.905851 -vn -0.196589 -0.693309 -0.693308 -vn -0.196590 -0.905851 -0.375215 -vn -0.196590 -0.980486 0.000000 -vn -0.196590 -0.905851 0.375216 -vn -0.196590 -0.693308 0.693308 -vn -0.196590 -0.375215 0.905851 -vn -0.196589 0.000001 0.980486 -vn -0.196590 0.375216 0.905851 -vn -0.196590 0.693308 0.693308 -vn -0.196590 0.905851 0.375216 -vn -1.000000 -0.000001 0.000000 -vn -1.000000 -0.000001 0.000000 -vn -1.000000 -0.000001 0.000000 -vn -1.000000 -0.000001 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 -0.000001 -0.000000 -vn -1.000000 -0.000001 -0.000000 -vn -1.000000 -0.000001 -0.000000 -vn -1.000000 -0.000001 -0.000000 -vn -1.000000 0.000001 -0.000000 -vn -1.000000 0.000001 -0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 0.000001 0.000000 -vn -1.000000 0.000001 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 0.000001 0.000000 -vn -1.000000 0.000001 0.000000 -vn -1.000000 0.000001 0.000000 -vn -1.000000 0.000001 0.000000 -vn 0.000000 1.000000 -0.000000 -vn -0.000000 1.000000 -0.000000 -s 1 -g Wheel_Rear_Left -usemtl initialShadingGroup -f 2/1/1 18/4/2 17/3/3 1/2/4 -f 3/5/5 19/6/6 18/4/2 2/1/1 -f 4/7/7 20/8/8 19/6/6 3/5/5 -f 5/9/9 21/10/10 20/8/8 4/7/7 -f 6/11/11 22/12/12 21/10/10 5/9/9 -f 7/13/13 23/14/14 22/12/12 6/11/11 -f 8/15/15 24/16/16 23/14/14 7/13/13 -f 9/17/17 25/18/18 24/16/16 8/15/15 -f 10/19/19 26/20/20 25/18/18 9/17/17 -f 11/21/21 27/22/22 26/20/20 10/19/19 -f 12/23/23 28/24/24 27/22/22 11/21/21 -f 13/25/25 29/26/26 28/24/24 12/23/23 -f 14/27/27 30/28/28 29/26/26 13/25/25 -f 15/29/29 31/30/30 30/28/28 14/27/27 -f 16/31/31 32/32/32 31/30/30 15/29/29 -f 1/33/4 17/34/3 32/32/32 16/31/31 -f 18/4/2 34/36/33 33/35/34 17/3/3 -f 19/6/6 35/37/35 34/36/33 18/4/2 -f 20/8/8 36/38/36 35/37/35 19/6/6 -f 21/10/10 37/39/37 36/38/36 20/8/8 -f 22/12/12 38/40/38 37/39/37 21/10/10 -f 23/14/14 39/41/39 38/40/38 22/12/12 -f 24/16/16 40/42/40 39/41/39 23/14/14 -f 27/22/22 42/44/41 41/43/42 26/20/20 -f 28/24/24 43/45/43 42/44/41 27/22/22 -f 29/26/26 44/46/44 43/45/43 28/24/24 -f 30/28/28 45/47/45 44/46/44 29/26/26 -f 31/30/30 46/48/46 45/47/45 30/28/28 -f 32/32/32 47/49/47 46/48/46 31/30/30 -f 17/34/3 33/50/34 47/49/47 32/32/32 -f 34/36/33 49/52/48 48/51/49 33/35/34 -f 35/37/35 50/53/50 49/52/48 34/36/33 -f 36/38/36 51/54/51 50/53/50 35/37/35 -f 37/39/37 52/55/52 51/54/51 36/38/36 -f 38/40/38 53/56/53 52/55/52 37/39/37 -f 39/41/39 54/57/54 53/56/53 38/40/38 -f 40/42/40 55/58/55 54/57/54 39/41/39 -f 42/44/41 58/60/56 57/59/57 41/43/42 -f 43/45/43 59/61/58 58/60/56 42/44/41 -f 44/46/44 60/62/59 59/61/58 43/45/43 -f 45/47/45 61/63/60 60/62/59 44/46/44 -f 46/48/46 62/64/61 61/63/60 45/47/45 -f 47/49/47 63/65/62 62/64/61 46/48/46 -f 33/50/34 48/66/49 63/65/62 47/49/47 -s 2 -f 49/52/63 65/68/64 64/67/65 48/51/66 -f 50/53/67 66/69/68 65/68/64 49/52/63 -f 51/54/69 67/70/70 66/69/68 50/53/67 -f 52/55/71 68/71/72 67/70/70 51/54/69 -f 53/56/73 69/72/74 68/71/72 52/55/71 -f 54/57/75 70/73/76 69/72/74 53/56/73 -f 55/58/77 71/74/78 70/73/76 54/57/75 -f 56/75/79 72/76/80 71/74/78 55/58/77 -f 57/59/81 73/77/82 72/76/80 56/75/79 -f 58/60/83 74/78/84 73/77/82 57/59/81 -f 59/61/85 75/79/86 74/78/84 58/60/83 -f 60/62/87 76/80/88 75/79/86 59/61/85 -f 61/63/89 77/81/90 76/80/88 60/62/87 -f 62/64/91 78/82/92 77/81/90 61/63/89 -f 63/65/93 79/83/94 78/82/92 62/64/91 -f 48/66/66 64/84/65 79/83/94 63/65/93 -s 3 -f 65/68/95 81/86/96 80/85/97 64/67/98 -f 66/69/99 82/87/100 81/86/96 65/68/95 -f 67/70/101 83/88/102 82/87/100 66/69/99 -f 68/71/103 84/89/104 83/88/102 67/70/101 -f 69/72/105 85/90/106 84/89/104 68/71/103 -f 70/73/107 86/91/108 85/90/106 69/72/105 -f 71/74/109 87/92/110 86/91/108 70/73/107 -f 72/76/111 88/93/112 87/92/110 71/74/109 -f 73/77/113 89/94/114 88/93/112 72/76/111 -f 74/78/115 90/95/116 89/94/114 73/77/113 -f 75/79/117 91/96/118 90/95/116 74/78/115 -f 76/80/119 92/97/120 91/96/118 75/79/117 -f 77/81/121 93/98/122 92/97/120 76/80/119 -f 78/82/123 94/99/124 93/98/122 77/81/121 -f 79/83/125 95/100/126 94/99/124 78/82/123 -f 64/84/98 80/101/97 95/100/126 79/83/125 -f 81/86/96 97/103/127 96/102/128 80/85/97 -f 82/87/100 98/104/129 97/103/127 81/86/96 -f 83/88/102 99/105/130 98/104/129 82/87/100 -f 84/89/104 100/106/131 99/105/130 83/88/102 -f 85/90/106 101/107/132 100/106/131 84/89/104 -f 86/91/108 102/108/133 101/107/132 85/90/106 -f 87/92/110 103/109/134 102/108/133 86/91/108 -f 88/93/112 104/110/135 103/109/134 87/92/110 -f 89/94/114 105/111/136 104/110/135 88/93/112 -f 90/95/116 106/112/137 105/111/136 89/94/114 -f 91/96/118 107/113/138 106/112/137 90/95/116 -f 92/97/120 108/114/139 107/113/138 91/96/118 -f 93/98/122 109/115/140 108/114/139 92/97/120 -f 94/99/124 110/116/141 109/115/140 93/98/122 -f 95/100/126 111/117/142 110/116/141 94/99/124 -f 80/101/97 96/118/128 111/117/142 95/100/126 -f 97/103/127 113/120/143 112/119/144 96/102/128 -f 98/104/129 114/121/145 113/120/143 97/103/127 -f 99/105/130 115/122/146 114/121/145 98/104/129 -f 100/106/131 116/123/147 115/122/146 99/105/130 -f 101/107/132 117/124/148 116/123/147 100/106/131 -f 102/108/133 118/125/149 117/124/148 101/107/132 -f 103/109/134 119/126/150 118/125/149 102/108/133 -f 104/110/135 120/127/151 119/126/150 103/109/134 -f 105/111/136 121/128/152 120/127/151 104/110/135 -f 106/112/137 122/129/153 121/128/152 105/111/136 -f 107/113/138 123/130/154 122/129/153 106/112/137 -f 108/114/139 124/131/155 123/130/154 107/113/138 -f 109/115/140 125/132/156 124/131/155 108/114/139 -f 110/116/141 126/133/157 125/132/156 109/115/140 -f 111/117/142 127/134/158 126/133/157 110/116/141 -f 96/118/128 112/135/144 127/134/158 111/117/142 -s 4 -f 113/120/159 2/137/160 1/136/161 112/119/162 -f 114/121/163 3/138/164 2/137/160 113/120/159 -f 115/122/165 4/139/166 3/138/164 114/121/163 -f 116/123/167 5/140/168 4/139/166 115/122/165 -f 117/124/169 6/141/170 5/140/168 116/123/167 -f 118/125/171 7/142/172 6/141/170 117/124/169 -f 119/126/173 8/143/174 7/142/172 118/125/171 -f 120/127/175 9/144/176 8/143/174 119/126/173 -f 121/128/177 10/145/178 9/144/176 120/127/175 -f 122/129/179 11/146/180 10/145/178 121/128/177 -f 123/130/181 12/147/182 11/146/180 122/129/179 -f 124/131/183 13/148/184 12/147/182 123/130/181 -f 125/132/185 14/149/186 13/148/184 124/131/183 -f 126/133/187 15/150/188 14/149/186 125/132/185 -f 127/134/189 16/151/190 15/150/188 126/133/187 -f 112/135/162 1/152/161 16/151/190 127/134/189 -s 1 -f 25/153/18 128/156/191 40/155/40 24/154/16 -f 26/157/20 41/160/42 128/159/191 25/158/18 -f 128/161/191 56/164/192 55/163/55 40/162/40 -f 41/165/42 57/168/57 56/167/192 128/166/191 diff --git a/models/LightCycle_Wheel_Rear_Right.obj b/models/LightCycle_Wheel_Rear_Right.obj deleted file mode 100644 index be59419..0000000 --- a/models/LightCycle_Wheel_Rear_Right.obj +++ /dev/null @@ -1,627 +0,0 @@ -# This file uses centimeters as units for non-parametric coordinates. - -mtllib LightCycle_Wheel_Rear_Right.mtl -g default -v 0.798836 0.861980 0.000000 -v 0.798836 0.796366 -0.329865 -v 0.798836 0.609512 -0.609512 -v 0.798836 0.329866 -0.796366 -v 0.798836 -0.000000 -0.861980 -v 0.798836 -0.329865 -0.796366 -v 0.798836 -0.609512 -0.609511 -v 0.798836 -0.796366 -0.329865 -v 0.798836 -0.861980 0.000000 -v 0.798836 -0.796365 0.329866 -v 0.798836 -0.609512 0.609512 -v 0.798836 -0.329865 0.796365 -v 0.798836 0.000000 0.861980 -v 0.798836 0.329866 0.796365 -v 0.798836 0.609512 0.609512 -v 0.798836 0.796366 0.329865 -v 0.266278 0.861980 0.000000 -v 0.266278 0.796366 -0.329865 -v 0.266278 0.609512 -0.609512 -v 0.266278 0.329866 -0.796366 -v 0.266278 -0.000000 -0.861980 -v 0.266278 -0.329865 -0.796366 -v 0.266278 -0.609512 -0.609511 -v 0.266278 -0.796366 -0.329865 -v 0.266278 -0.861980 0.000000 -v 0.266278 -0.796365 0.329866 -v 0.266278 -0.609512 0.609512 -v 0.266278 -0.329865 0.796365 -v 0.266278 0.000000 0.861980 -v 0.266278 0.329866 0.796365 -v 0.266278 0.609512 0.609512 -v 0.266278 0.796366 0.329865 -v -0.266279 0.861980 0.000000 -v -0.266279 0.796366 -0.329865 -v -0.266279 0.609512 -0.609512 -v -0.266279 0.329866 -0.796366 -v -0.266279 -0.000000 -0.861980 -v -0.266279 -0.329865 -0.796366 -v -0.266279 -0.609512 -0.609511 -v -0.266279 -0.796366 -0.329865 -v -0.266279 -0.796365 0.329866 -v -0.266279 -0.609512 0.609512 -v -0.266279 -0.329865 0.796365 -v -0.266279 0.000000 0.861980 -v -0.266279 0.329866 0.796365 -v -0.266279 0.609512 0.609512 -v -0.266279 0.796366 0.329865 -v -0.798836 0.861980 0.000000 -v -0.798836 0.796366 -0.329865 -v -0.798836 0.609512 -0.609512 -v -0.798836 0.329866 -0.796366 -v -0.798836 0.000000 -0.861980 -v -0.798836 -0.329865 -0.796366 -v -0.798836 -0.609512 -0.609511 -v -0.798836 -0.796366 -0.329865 -v -0.798836 -0.861980 0.000000 -v -0.798836 -0.796365 0.329866 -v -0.798836 -0.609512 0.609512 -v -0.798836 -0.329865 0.796365 -v -0.798836 0.000000 0.861980 -v -0.798836 0.329866 0.796365 -v -0.798836 0.609512 0.609512 -v -0.798836 0.796366 0.329865 -v -0.798836 1.149307 0.000000 -v -0.798836 1.061821 -0.439821 -v -0.798836 0.812683 -0.812683 -v -0.798836 0.439821 -1.061821 -v -0.798836 0.000000 -1.149307 -v -0.798836 -0.439821 -1.061821 -v -0.798836 -0.812683 -0.812682 -v -0.798836 -1.061821 -0.439820 -v -0.798836 -1.149307 0.000001 -v -0.798836 -1.061821 0.439821 -v -0.798836 -0.812682 0.812683 -v -0.798836 -0.439820 1.061821 -v -0.798836 0.000001 1.149307 -v -0.798836 0.439821 1.061821 -v -0.798836 0.812683 0.812682 -v -0.798836 1.061821 0.439820 -v -0.289920 1.251346 0.000000 -v -0.289920 1.156093 -0.478869 -v -0.289920 0.884835 -0.884835 -v -0.289920 0.478869 -1.156093 -v -0.289920 -0.000000 -1.251345 -v -0.289920 -0.478870 -1.156092 -v -0.289920 -0.884835 -0.884835 -v -0.289920 -1.156093 -0.478869 -v -0.289920 -1.251346 0.000001 -v -0.289920 -1.156092 0.478870 -v -0.289920 -0.884835 0.884835 -v -0.289920 -0.478869 1.156093 -v -0.289920 0.000001 1.251345 -v -0.289920 0.478870 1.156092 -v -0.289920 0.884835 0.884835 -v -0.289920 1.156093 0.478869 -v 0.289919 1.251346 0.000000 -v 0.289919 1.156092 -0.478869 -v 0.289919 0.884835 -0.884835 -v 0.289919 0.478869 -1.156093 -v 0.289919 -0.000000 -1.251345 -v 0.289919 -0.478870 -1.156092 -v 0.289919 -0.884835 -0.884835 -v 0.289919 -1.156093 -0.478869 -v 0.289919 -1.251346 0.000001 -v 0.289919 -1.156092 0.478870 -v 0.289919 -0.884835 0.884835 -v 0.289919 -0.478869 1.156093 -v 0.289919 0.000001 1.251345 -v 0.289919 0.478870 1.156092 -v 0.289919 0.884835 0.884835 -v 0.289919 1.156093 0.478869 -v 0.798836 1.149307 0.000000 -v 0.798836 1.061821 -0.439821 -v 0.798836 0.812683 -0.812683 -v 0.798836 0.439821 -1.061821 -v 0.798836 -0.000000 -1.149307 -v 0.798836 -0.439821 -1.061821 -v 0.798836 -0.812683 -0.812682 -v 0.798836 -1.061821 -0.439820 -v 0.798836 -1.149307 0.000001 -v 0.798836 -1.061821 0.439821 -v 0.798836 -0.812682 0.812683 -v 0.798836 -0.439820 1.061821 -v 0.798836 0.000001 1.149307 -v 0.798836 0.439821 1.061821 -v 0.798836 0.812683 0.812682 -v 0.798836 1.061821 0.439820 -v -0.266279 -0.861980 0.000000 -vt 0.062500 1.000000 -vt 0.000000 1.000000 -vt 0.000000 0.875000 -vt 0.062500 0.875000 -vt 0.125000 1.000000 -vt 0.125000 0.875000 -vt 0.187500 1.000000 -vt 0.187500 0.875000 -vt 0.250000 1.000000 -vt 0.250000 0.875000 -vt 0.312500 1.000000 -vt 0.312500 0.875000 -vt 0.375000 1.000000 -vt 0.375000 0.875000 -vt 0.437500 1.000000 -vt 0.437500 0.875000 -vt 0.500000 1.000000 -vt 0.500000 0.875000 -vt 0.562500 1.000000 -vt 0.562500 0.875000 -vt 0.625000 1.000000 -vt 0.625000 0.875000 -vt 0.687500 1.000000 -vt 0.687500 0.875000 -vt 0.750000 1.000000 -vt 0.750000 0.875000 -vt 0.812500 1.000000 -vt 0.812500 0.875000 -vt 0.875000 1.000000 -vt 0.875000 0.875000 -vt 0.937500 1.000000 -vt 0.937500 0.875000 -vt 1.000000 1.000000 -vt 1.000000 0.875000 -vt 0.000000 0.750000 -vt 0.062500 0.750000 -vt 0.125000 0.750000 -vt 0.187500 0.750000 -vt 0.250000 0.750000 -vt 0.312500 0.750000 -vt 0.375000 0.750000 -vt 0.437500 0.750000 -vt 0.562500 0.750000 -vt 0.625000 0.750000 -vt 0.687500 0.750000 -vt 0.750000 0.750000 -vt 0.812500 0.750000 -vt 0.875000 0.750000 -vt 0.937500 0.750000 -vt 1.000000 0.750000 -vt 0.000000 0.625000 -vt 0.062500 0.625000 -vt 0.125000 0.625000 -vt 0.187500 0.625000 -vt 0.250000 0.625000 -vt 0.312500 0.625000 -vt 0.375000 0.625000 -vt 0.437500 0.625000 -vt 0.562500 0.625000 -vt 0.625000 0.625000 -vt 0.687500 0.625000 -vt 0.750000 0.625000 -vt 0.812500 0.625000 -vt 0.875000 0.625000 -vt 0.937500 0.625000 -vt 1.000000 0.625000 -vt 0.000000 0.500000 -vt 0.062500 0.500000 -vt 0.125000 0.500000 -vt 0.187500 0.500000 -vt 0.250000 0.500000 -vt 0.312500 0.500000 -vt 0.375000 0.500000 -vt 0.437500 0.500000 -vt 0.500000 0.625000 -vt 0.500000 0.500000 -vt 0.562500 0.500000 -vt 0.625000 0.500000 -vt 0.687500 0.500000 -vt 0.750000 0.500000 -vt 0.812500 0.500000 -vt 0.875000 0.500000 -vt 0.937500 0.500000 -vt 1.000000 0.500000 -vt 0.000000 0.375000 -vt 0.062500 0.375000 -vt 0.125000 0.375000 -vt 0.187500 0.375000 -vt 0.250000 0.375000 -vt 0.312500 0.375000 -vt 0.375000 0.375000 -vt 0.437500 0.375000 -vt 0.500000 0.375000 -vt 0.562500 0.375000 -vt 0.625000 0.375000 -vt 0.687500 0.375000 -vt 0.750000 0.375000 -vt 0.812500 0.375000 -vt 0.875000 0.375000 -vt 0.937500 0.375000 -vt 1.000000 0.375000 -vt 0.000000 0.250000 -vt 0.062500 0.250000 -vt 0.125000 0.250000 -vt 0.187500 0.250000 -vt 0.250000 0.250000 -vt 0.312500 0.250000 -vt 0.375000 0.250000 -vt 0.437500 0.250000 -vt 0.500000 0.250000 -vt 0.562500 0.250000 -vt 0.625000 0.250000 -vt 0.687500 0.250000 -vt 0.750000 0.250000 -vt 0.812500 0.250000 -vt 0.875000 0.250000 -vt 0.937500 0.250000 -vt 1.000000 0.250000 -vt 0.000000 0.125000 -vt 0.062500 0.125000 -vt 0.125000 0.125000 -vt 0.187500 0.125000 -vt 0.250000 0.125000 -vt 0.312500 0.125000 -vt 0.375000 0.125000 -vt 0.437500 0.125000 -vt 0.500000 0.125000 -vt 0.562500 0.125000 -vt 0.625000 0.125000 -vt 0.687500 0.125000 -vt 0.750000 0.125000 -vt 0.812500 0.125000 -vt 0.875000 0.125000 -vt 0.937500 0.125000 -vt 1.000000 0.125000 -vt 0.000000 0.000000 -vt 0.062500 0.000000 -vt 0.125000 0.000000 -vt 0.187500 0.000000 -vt 0.250000 0.000000 -vt 0.312500 0.000000 -vt 0.375000 0.000000 -vt 0.437500 0.000000 -vt 0.500000 0.000000 -vt 0.562500 0.000000 -vt 0.625000 0.000000 -vt 0.687500 0.000000 -vt 0.750000 0.000000 -vt 0.812500 0.000000 -vt 0.875000 0.000000 -vt 0.937500 0.000000 -vt 1.000000 0.000000 -vt 0.000000 0.000000 -vt 1.000000 0.000000 -vt 1.000000 1.000000 -vt 0.000000 1.000000 -vt 0.000000 0.000000 -vt 1.000000 0.000000 -vt 1.000000 1.000000 -vt 0.000000 1.000000 -vt 0.000000 0.000000 -vt 1.000000 0.000000 -vt 1.000000 1.000000 -vt 0.000000 1.000000 -vt 0.000000 0.000000 -vt 1.000000 0.000000 -vt 1.000000 1.000000 -vt 0.000000 1.000000 -vn 0.000000 -0.923879 0.382684 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -0.923880 0.382684 -vn -0.000000 -0.707107 0.707107 -vn -0.000000 -0.707107 0.707107 -vn -0.000000 -0.382683 0.923880 -vn -0.000000 -0.382683 0.923880 -vn 0.000000 0.000000 1.000000 -vn -0.000000 0.000000 1.000000 -vn 0.000000 0.382684 0.923879 -vn -0.000000 0.382684 0.923879 -vn 0.000000 0.707107 0.707107 -vn 0.000000 0.707107 0.707107 -vn 0.000000 0.923880 0.382684 -vn -0.000000 0.923879 0.382684 -vn 0.000000 1.000000 -0.000000 -vn -0.000000 1.000000 -0.000000 -vn -0.000000 0.923879 -0.382684 -vn -0.000000 0.923879 -0.382684 -vn -0.000000 0.707107 -0.707107 -vn -0.000000 0.707107 -0.707107 -vn 0.000000 0.382683 -0.923880 -vn -0.000000 0.382683 -0.923880 -vn 0.000000 -0.000000 -1.000000 -vn -0.000000 -0.000000 -1.000000 -vn 0.000000 -0.382684 -0.923879 -vn -0.000000 -0.382684 -0.923879 -vn 0.000000 -0.707107 -0.707107 -vn -0.000000 -0.707107 -0.707107 -vn 0.000000 -0.923879 -0.382684 -vn 0.000000 -0.923879 -0.382684 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -0.923880 0.382683 -vn 0.000000 -0.707107 0.707107 -vn 0.000000 -0.382684 0.923880 -vn 0.000000 0.000000 1.000000 -vn -0.000000 0.382684 0.923879 -vn 0.000000 0.707107 0.707107 -vn 0.000000 0.923879 0.382684 -vn -0.000000 0.923879 -0.382684 -vn -0.000000 0.707107 -0.707107 -vn -0.000000 0.382683 -0.923880 -vn -0.000000 -0.000000 -1.000000 -vn -0.000000 -0.382684 -0.923879 -vn -0.000000 -0.707107 -0.707107 -vn 0.000000 -0.923880 -0.382684 -vn 0.000000 -1.000000 -0.000000 -vn 0.000000 -0.923880 0.382683 -vn 0.000000 -0.707107 0.707107 -vn 0.000000 -0.382684 0.923880 -vn 0.000000 0.000000 1.000000 -vn 0.000000 0.382684 0.923879 -vn 0.000000 0.707107 0.707107 -vn 0.000000 0.923879 0.382684 -vn 0.000000 0.923879 -0.382684 -vn 0.000000 0.707107 -0.707107 -vn 0.000000 0.382683 -0.923880 -vn 0.000000 -0.000000 -1.000000 -vn 0.000000 -0.382684 -0.923880 -vn 0.000000 -0.707107 -0.707107 -vn 0.000000 -0.923880 -0.382683 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 -0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -1.000000 0.000000 0.000000 -vn -0.196589 0.905851 -0.375216 -vn -0.196590 0.980486 -0.000000 -vn -0.098814 0.995106 -0.000000 -vn -0.098814 0.919358 -0.380811 -vn -0.196589 0.693308 -0.693308 -vn -0.098814 0.703646 -0.703646 -vn -0.196590 0.375215 -0.905851 -vn -0.098815 0.380810 -0.919358 -vn -0.196591 -0.000000 -0.980486 -vn -0.098815 -0.000000 -0.995106 -vn -0.196590 -0.375216 -0.905851 -vn -0.098814 -0.380811 -0.919358 -vn -0.196590 -0.693308 -0.693308 -vn -0.098814 -0.703646 -0.703646 -vn -0.196590 -0.905851 -0.375215 -vn -0.098814 -0.919358 -0.380810 -vn -0.196590 -0.980486 0.000000 -vn -0.098814 -0.995106 0.000000 -vn -0.196590 -0.905851 0.375216 -vn -0.098814 -0.919358 0.380811 -vn -0.196590 -0.693308 0.693308 -vn -0.098814 -0.703646 0.703646 -vn -0.196590 -0.375215 0.905851 -vn -0.098814 -0.380810 0.919358 -vn -0.196590 0.000001 0.980486 -vn -0.098814 0.000001 0.995106 -vn -0.196590 0.375216 0.905851 -vn -0.098814 0.380811 0.919358 -vn -0.196590 0.693308 0.693308 -vn -0.098814 0.703646 0.703646 -vn -0.196590 0.905851 0.375216 -vn -0.098815 0.919358 0.380810 -vn 0.098814 0.995106 -0.000000 -vn 0.098814 0.919358 -0.380811 -vn 0.098814 0.703646 -0.703646 -vn 0.098815 0.380810 -0.919358 -vn 0.098815 -0.000000 -0.995106 -vn 0.098814 -0.380811 -0.919358 -vn 0.098814 -0.703646 -0.703646 -vn 0.098814 -0.919358 -0.380810 -vn 0.098814 -0.995106 0.000000 -vn 0.098814 -0.919358 0.380811 -vn 0.098815 -0.703646 0.703646 -vn 0.098814 -0.380810 0.919358 -vn 0.098814 0.000001 0.995106 -vn 0.098814 0.380811 0.919358 -vn 0.098814 0.703646 0.703646 -vn 0.098814 0.919358 0.380810 -vn 0.196589 0.980486 -0.000000 -vn 0.196589 0.905851 -0.375216 -vn 0.196589 0.693308 -0.693308 -vn 0.196590 0.375215 -0.905851 -vn 0.196591 -0.000000 -0.980486 -vn 0.196590 -0.375216 -0.905851 -vn 0.196589 -0.693308 -0.693308 -vn 0.196590 -0.905851 -0.375215 -vn 0.196590 -0.980486 0.000000 -vn 0.196590 -0.905851 0.375216 -vn 0.196590 -0.693308 0.693308 -vn 0.196590 -0.375215 0.905851 -vn 0.196590 0.000001 0.980486 -vn 0.196590 0.375216 0.905851 -vn 0.196590 0.693308 0.693308 -vn 0.196590 0.905851 0.375216 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 -0.000000 -0.000000 -vn 1.000000 -0.000000 -0.000000 -vn 1.000000 -0.000001 -0.000000 -vn 1.000000 -0.000001 -0.000000 -vn 1.000000 -0.000001 -0.000000 -vn 1.000000 -0.000001 -0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000001 0.000000 -vn 1.000000 0.000001 0.000000 -vn 1.000000 0.000001 0.000000 -vn 1.000000 0.000001 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn 1.000000 -0.000000 0.000000 -vn -0.000000 1.000000 -0.000000 -vn 0.000000 1.000000 -0.000000 -s 1 -g Wheel_Rear_Right -usemtl initialShadingGroup -f 2/1/1 1/2/2 17/3/3 18/4/4 -f 3/5/5 2/1/1 18/4/4 19/6/6 -f 4/7/7 3/5/5 19/6/6 20/8/8 -f 5/9/9 4/7/7 20/8/8 21/10/10 -f 6/11/11 5/9/9 21/10/10 22/12/12 -f 7/13/13 6/11/11 22/12/12 23/14/14 -f 8/15/15 7/13/13 23/14/14 24/16/16 -f 9/17/17 8/15/15 24/16/16 25/18/18 -f 10/19/19 9/17/17 25/18/18 26/20/20 -f 11/21/21 10/19/19 26/20/20 27/22/22 -f 12/23/23 11/21/21 27/22/22 28/24/24 -f 13/25/25 12/23/23 28/24/24 29/26/26 -f 14/27/27 13/25/25 29/26/26 30/28/28 -f 15/29/29 14/27/27 30/28/28 31/30/30 -f 16/31/31 15/29/29 31/30/30 32/32/32 -f 1/33/2 16/31/31 32/32/32 17/34/3 -f 18/4/4 17/3/3 33/35/33 34/36/34 -f 19/6/6 18/4/4 34/36/34 35/37/35 -f 20/8/8 19/6/6 35/37/35 36/38/36 -f 21/10/10 20/8/8 36/38/36 37/39/37 -f 22/12/12 21/10/10 37/39/37 38/40/38 -f 23/14/14 22/12/12 38/40/38 39/41/39 -f 24/16/16 23/14/14 39/41/39 40/42/40 -f 27/22/22 26/20/20 41/43/41 42/44/42 -f 28/24/24 27/22/22 42/44/42 43/45/43 -f 29/26/26 28/24/24 43/45/43 44/46/44 -f 30/28/28 29/26/26 44/46/44 45/47/45 -f 31/30/30 30/28/28 45/47/45 46/48/46 -f 32/32/32 31/30/30 46/48/46 47/49/47 -f 17/34/3 32/32/32 47/49/47 33/50/33 -f 34/36/34 33/35/33 48/51/48 49/52/49 -f 35/37/35 34/36/34 49/52/49 50/53/50 -f 36/38/36 35/37/35 50/53/50 51/54/51 -f 37/39/37 36/38/36 51/54/51 52/55/52 -f 38/40/38 37/39/37 52/55/52 53/56/53 -f 39/41/39 38/40/38 53/56/53 54/57/54 -f 40/42/40 39/41/39 54/57/54 55/58/55 -f 42/44/42 41/43/41 57/59/56 58/60/57 -f 43/45/43 42/44/42 58/60/57 59/61/58 -f 44/46/44 43/45/43 59/61/58 60/62/59 -f 45/47/45 44/46/44 60/62/59 61/63/60 -f 46/48/46 45/47/45 61/63/60 62/64/61 -f 47/49/47 46/48/46 62/64/61 63/65/62 -f 33/50/33 47/49/47 63/65/62 48/66/48 -s 2 -f 49/52/63 48/51/64 64/67/65 65/68/66 -f 50/53/67 49/52/63 65/68/66 66/69/68 -f 51/54/69 50/53/67 66/69/68 67/70/70 -f 52/55/71 51/54/69 67/70/70 68/71/72 -f 53/56/73 52/55/71 68/71/72 69/72/74 -f 54/57/75 53/56/73 69/72/74 70/73/76 -f 55/58/77 54/57/75 70/73/76 71/74/78 -f 56/75/79 55/58/77 71/74/78 72/76/80 -f 57/59/81 56/75/79 72/76/80 73/77/82 -f 58/60/83 57/59/81 73/77/82 74/78/84 -f 59/61/85 58/60/83 74/78/84 75/79/86 -f 60/62/87 59/61/85 75/79/86 76/80/88 -f 61/63/89 60/62/87 76/80/88 77/81/90 -f 62/64/91 61/63/89 77/81/90 78/82/92 -f 63/65/93 62/64/91 78/82/92 79/83/94 -f 48/66/64 63/65/93 79/83/94 64/84/65 -s 3 -f 65/68/95 64/67/96 80/85/97 81/86/98 -f 66/69/99 65/68/95 81/86/98 82/87/100 -f 67/70/101 66/69/99 82/87/100 83/88/102 -f 68/71/103 67/70/101 83/88/102 84/89/104 -f 69/72/105 68/71/103 84/89/104 85/90/106 -f 70/73/107 69/72/105 85/90/106 86/91/108 -f 71/74/109 70/73/107 86/91/108 87/92/110 -f 72/76/111 71/74/109 87/92/110 88/93/112 -f 73/77/113 72/76/111 88/93/112 89/94/114 -f 74/78/115 73/77/113 89/94/114 90/95/116 -f 75/79/117 74/78/115 90/95/116 91/96/118 -f 76/80/119 75/79/117 91/96/118 92/97/120 -f 77/81/121 76/80/119 92/97/120 93/98/122 -f 78/82/123 77/81/121 93/98/122 94/99/124 -f 79/83/125 78/82/123 94/99/124 95/100/126 -f 64/84/96 79/83/125 95/100/126 80/101/97 -f 81/86/98 80/85/97 96/102/127 97/103/128 -f 82/87/100 81/86/98 97/103/128 98/104/129 -f 83/88/102 82/87/100 98/104/129 99/105/130 -f 84/89/104 83/88/102 99/105/130 100/106/131 -f 85/90/106 84/89/104 100/106/131 101/107/132 -f 86/91/108 85/90/106 101/107/132 102/108/133 -f 87/92/110 86/91/108 102/108/133 103/109/134 -f 88/93/112 87/92/110 103/109/134 104/110/135 -f 89/94/114 88/93/112 104/110/135 105/111/136 -f 90/95/116 89/94/114 105/111/136 106/112/137 -f 91/96/118 90/95/116 106/112/137 107/113/138 -f 92/97/120 91/96/118 107/113/138 108/114/139 -f 93/98/122 92/97/120 108/114/139 109/115/140 -f 94/99/124 93/98/122 109/115/140 110/116/141 -f 95/100/126 94/99/124 110/116/141 111/117/142 -f 80/101/97 95/100/126 111/117/142 96/118/127 -f 97/103/128 96/102/127 112/119/143 113/120/144 -f 98/104/129 97/103/128 113/120/144 114/121/145 -f 99/105/130 98/104/129 114/121/145 115/122/146 -f 100/106/131 99/105/130 115/122/146 116/123/147 -f 101/107/132 100/106/131 116/123/147 117/124/148 -f 102/108/133 101/107/132 117/124/148 118/125/149 -f 103/109/134 102/108/133 118/125/149 119/126/150 -f 104/110/135 103/109/134 119/126/150 120/127/151 -f 105/111/136 104/110/135 120/127/151 121/128/152 -f 106/112/137 105/111/136 121/128/152 122/129/153 -f 107/113/138 106/112/137 122/129/153 123/130/154 -f 108/114/139 107/113/138 123/130/154 124/131/155 -f 109/115/140 108/114/139 124/131/155 125/132/156 -f 110/116/141 109/115/140 125/132/156 126/133/157 -f 111/117/142 110/116/141 126/133/157 127/134/158 -f 96/118/127 111/117/142 127/134/158 112/135/143 -s 4 -f 113/120/159 112/119/160 1/136/161 2/137/162 -f 114/121/163 113/120/159 2/137/162 3/138/164 -f 115/122/165 114/121/163 3/138/164 4/139/166 -f 116/123/167 115/122/165 4/139/166 5/140/168 -f 117/124/169 116/123/167 5/140/168 6/141/170 -f 118/125/171 117/124/169 6/141/170 7/142/172 -f 119/126/173 118/125/171 7/142/172 8/143/174 -f 120/127/175 119/126/173 8/143/174 9/144/176 -f 121/128/177 120/127/175 9/144/176 10/145/178 -f 122/129/179 121/128/177 10/145/178 11/146/180 -f 123/130/181 122/129/179 11/146/180 12/147/182 -f 124/131/183 123/130/181 12/147/182 13/148/184 -f 125/132/185 124/131/183 13/148/184 14/149/186 -f 126/133/187 125/132/185 14/149/186 15/150/188 -f 127/134/189 126/133/187 15/150/188 16/151/190 -f 112/135/160 127/134/189 16/151/190 1/152/161 -s 1 -f 25/153/18 24/154/16 40/155/40 128/156/191 -f 26/157/20 25/158/18 128/159/191 41/160/41 -f 128/161/191 40/162/40 55/163/55 56/164/192 -f 41/165/41 128/166/191 56/167/192 57/168/56
leonardteo/OBJViewer
280814cf7dda11891f2e8dd2abc1721b4a0194b1
Camera is working
diff --git a/CameraNode.cpp b/CameraNode.cpp index 94c5a7c..e4a63f2 100644 --- a/CameraNode.cpp +++ b/CameraNode.cpp @@ -1,32 +1,122 @@ /* * Camera.cpp * OBJViewer * * Created by Leonard Teo on 10-10-06. * Copyright 2010 Leonard Teo. All rights reserved. * */ #include "CameraNode.h" -CameraNode::CameraNode() +CameraNode::CameraNode(CameraType cameraType) : Node() { //Set node type this->type = CAMERA; + this->cameraType = cameraType; //Polar camera settings - this->point_of_interest = new Vector3(0.0, 0.0, 0.0); - this->azimuth = -45; - this->elevation = 30; - this->twist = 0; - this->distance = 15; - this->near_plane = 0.1f; - this->far_plane = 100; + this->azimuth = 0.0; + this->elevation = 0.0; + this->twist = 0.0; + this->distance = 0.0; + this->panX = 0.0; + this->panY = 0.0; + + this->azimuth_offset = 0.0; + this->elevation_offset = 0.0; + this->twist_offset = 0.0; + this->distance_offset = 0.0; + this->panX_offset = 0.0; + this->panY_offset = 0.0; + + //Default Projection settings + this->nearPlane = 0.1f; + this->farPlane = 500.0f; this->fov = 45; - this->perspective_mode = true; - this->ortho_zoom = 2; + this->perspectiveMode = true; + + this->orthoZoom = 2; + } CameraNode::~CameraNode() { + delete this; +} + +/** +Sets up a projection for the camera +Must provide viewport width and height +**/ +void CameraNode::setProjection(int width, int height) +{ + glViewport(0, 0, (GLsizei) width, (GLsizei) height); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + + //Perspective mode or ortho + float aspect_ratio = (float)width / (float)height; + + if (this->perspectiveMode){ + //If perspective mode, set up a perspective projection + gluPerspective(this->fov, GLfloat(aspect_ratio), this->nearPlane, this->farPlane); + + } else { + //If orthographic mode, set up an orthographic projection + + //Keep aspect ratio + float left, right, bottom, top; + + if (aspect_ratio < 1.0){ + left = -this->orthoZoom; + right = this->orthoZoom; + bottom = -this->orthoZoom * ( 1.0f / aspect_ratio ); + top = this->orthoZoom * ( 1.0f / aspect_ratio ); + } else { + left = -this->orthoZoom * aspect_ratio; + right = this->orthoZoom * aspect_ratio; + bottom = -this->orthoZoom; + top = this->orthoZoom; + } + glOrtho(left, right, bottom, top, -this->farPlane, this->farPlane); + } } + +/** +View transformations +**/ +void CameraNode::viewTransform() +{ + //If first person + if (this->cameraType == FIRSTPERSON){ + //To do: Make this rotate on a local, orthonormal basis + glRotatef(this->rotate->z, 0.0f, 0.0f, 1.0f); //Roll + glRotatef(this->rotate->y, 0.0f, 1.0f, 0.0f); //Pitch + glRotatef(this->rotate->x, 1.0f, 0.0f, 0.0f); //Heading + glTranslatef(-this->translate->x, -this->translate->y, -this->translate->z); + + } else + { + //If third person + glTranslatef(-((GLfloat)this->panX + (GLfloat)this->panX_offset), -((GLfloat)this->panY + (GLfloat)this->panY_offset), -( (GLfloat)this->distance + (GLfloat)this->distance_offset) ); //Translate along the z axis away from camera + glRotatef((GLfloat)this->twist + (GLfloat)this->twist_offset, (GLfloat)0.0, (GLfloat)0.0, (GLfloat)1.0); //Rotate around z axis (usually by 0) + glRotatef((GLfloat)this->elevation + (GLfloat)this->elevation_offset, (GLfloat)1.0, (GLfloat)0.0, (GLfloat)0.0); //Rotate around x axis + glRotatef((GLfloat)this->azimuth + (GLfloat)this->azimuth_offset, (GLfloat)0.0, (GLfloat)1.0, (GLfloat)0.0); //Rotate around y axis + + //To do: Make this rotate on a local, orthonormal basis + glRotatef(this->rotate->z, 0.0f, 0.0f, 1.0f); //Roll + glRotatef(this->rotate->y, 0.0f, 1.0f, 0.0f); //Pitch + glRotatef(this->rotate->x, 1.0f, 0.0f, 0.0f); //Heading + glTranslatef(-this->translate->x, -this->translate->y, -this->translate->z); + } + + + + //Call parent viewTransform + if (this->parent != NULL) + { + this->parent->viewTransform(); + } + +} \ No newline at end of file diff --git a/CameraNode.h b/CameraNode.h index 08f8f87..a70551e 100644 --- a/CameraNode.h +++ b/CameraNode.h @@ -1,60 +1,85 @@ /* * Camera.h * OBJViewer * * Created by Leonard Teo on 10-10-06. * Copyright 2010 Leonard Teo. All rights reserved. * */ #ifndef CAMERANODE_H #define CAMERANODE_H #include "Node.h" -#include "Vector3.h" + +#include <GL/glew.h> + +#ifdef __APPLE__ + #include <OpenGL/gl.h> + #include <OpenGL/glu.h> + #include <GLUT/GLUT.h> +#else + #include <GL/glut.h> +#endif enum CameraProjection { PERSPECTIVE, ORTHO }; enum CameraType { POLAR, FIRSTPERSON }; /** * Camera class extends Node */ class CameraNode : public Node { public: //Data Members CameraProjection cameraProjection; CameraType cameraType; //Constructor/Destructor - CameraNode(); + CameraNode(CameraType); ~CameraNode(); - //@todo: Should these be private? + //@todo: Should these be private? //Members - Vector3* point_of_interest; //Where the camera should be looking at + //Third person camera / polar camera float twist; //Roll float elevation; //Pitch float azimuth; //Heading - float distance; //Distance from point of interest + float distance; //Distance from point of interest (assume local origin) + float panX; //Used for panning the camera + float panY; + + //Third person offsets - used for controlling mouse movements where you don't want to write directly to the twist, elevation, azimuth + float twist_offset; + float elevation_offset; + float azimuth_offset; + float distance_offset; + float panX_offset; + float panY_offset; + + + //Projection settings float fov; //Field of View - float near_plane; //Near clipping plane - float far_plane; //Far clipping plane + float nearPlane; //Near clipping plane + float farPlane; //Far clipping plane - bool perspective_mode; //Switch between perspective and ortho + bool perspectiveMode; //Switch between perspective and ortho //Ortho - float ortho_zoom; //The orthographic zoom factor + float orthoZoom; //The orthographic zoom factor + //Methods + void setProjection(int width, int height); + void viewTransform(); }; #endif diff --git a/Node.cpp b/Node.cpp index 1ffa071..c7065c3 100644 --- a/Node.cpp +++ b/Node.cpp @@ -1,56 +1,72 @@ /* * Node.cpp * OBJViewer * * Created by Leonard Teo on 10-10-05. * */ #include "Node.h" //Constructor Node::Node() { + this->parent = NULL; this->children = new vector<Node*>; - this->scale = new Vector3(); + this->scale = new Vector3(1.0f, 1.0f, 1.0f); this->rotate = new Vector3(); this->translate = new Vector3(); this->id = ""; //Blank ID? } //Destructor Node::~Node() { this->children->clear(); delete this->children; delete this->scale; delete this->rotate; delete this->translate; delete this; } //Add a child void Node::addChild(Node* child) { //Set the child node's parent as this one child->setParent(this); //Add the child node this->children->push_back(child); } //Set the parent void Node::setParent(Node* parent) { this->parent = parent; } //Abstract method for rendering - must be overloaded by child classes void Node::render() { for (int i=0; i<this->children->size(); i++) { this->children->at(i)->render(); } +} + +//Abstract method for doing view transformations +void Node::viewTransform() +{ + //To do: Make this rotate on a local, orthonormal basis + glRotatef(-this->rotate->z, 0.0f, 0.0f, 1.0f); //Roll + glRotatef(-this->rotate->y, 0.0f, 1.0f, 0.0f); //Pitch + glRotatef(-this->rotate->x, 1.0f, 0.0f, 0.0f); //Heading + glTranslatef(-this->translate->x, -this->translate->y, -this->translate->z); + + if (this->parent != NULL) + { + this->parent->viewTransform(); + } } \ No newline at end of file diff --git a/Node.h b/Node.h index adef8a2..c012f90 100644 --- a/Node.h +++ b/Node.h @@ -1,47 +1,58 @@ /* * Node.h * OBJViewer * * Created by Leonard Teo on 10-10-05. * */ #ifndef NODE_H #define NODE_H #include <vector> -#include "Vector3.h" #include <string> + +#include <GL/glew.h> + +#ifdef __APPLE__ + #include <OpenGL/gl.h> + #include <OpenGL/glu.h> + #include <GLUT/GLUT.h> +#else + #include <GL/glut.h> +#endif + +#include "Vector3.h" + using namespace std; enum NodeType { POLYMESH, CAMERA, LIGHT, TRANSFORM }; class Node { public: //Data Members NodeType type; //The type of node this is vector<Node*>* children; //Child nodes Node* parent; //The node's parent string id; //The node's ID so that we can search for a node //Local Transforms Vector3* scale; //Local scaling Vector3* rotate; //Local rotation on x, y, z axes Vector3* translate; //Local translation //Methods Node(); ~Node(); void addChild(Node*); void setParent(Node*); virtual void render(); - -private: + virtual void viewTransform(); }; #endif diff --git a/OBJViewer.cpp b/OBJViewer.cpp index 6fa2670..23d4434 100644 --- a/OBJViewer.cpp +++ b/OBJViewer.cpp @@ -1,751 +1,835 @@ /** OBJ Viewer **/ //STD libraries #include <iostream> #include <string> //OpenGL libraries #include <GL/glew.h> #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/GLUT.h> #else #include <GL/glut.h> #endif //Engine libraries #include "OBJModel.h" #include "MyBitmap.h" #include "Node.h" #include "TransformNode.h" #include "PolyMeshNode.h" #include "Texture.h" #include "Vector3.h" +#include "CameraNode.h" #include "PolarCamera.h" using namespace std; //Default Screen Size const int WIDTH = 640; const int HEIGHT = 480; /** Global Variables **/ //Temporary screen width and height int width = WIDTH; int height = HEIGHT; //Mouse position int mouse_x; int mouse_y; int mouse_down_x; //Mouse position when a user clicks int mouse_down_y; //Mouse clicks states bool left_mouse_down = false; bool middle_mouse_down = false; bool right_mouse_down = false; //Model type int model = 0; //Show Wireframe bool show_wireframe = false; bool shaded_mode = true; //Camera - Polar view PolarCamera* camera = new PolarCamera(); +//Scene Graph Camera +CameraNode* sgCamera; + //Temporary variables to facilitate Polar camera float azimuth_change = 0; float twist_change = 0; float elevation_change = 0; float cam_distance_change = 0.0; //Panning temporary variables float pan_x_down = 0; //When the pan button is pushed, record this float pan_y_down = 0; float pan_z_down = 0; float pan_x_change = 0; float pan_y_change = 0; //Orthographic zooming temporary variable float ortho_zoom_change = 0; -//OBJ Models -//OBJModel* objmodel; //Any objmodel for testing -OBJModel* m1abrams; -OBJModel* humveehardtop; -OBJModel* uhtiger; //Texture MyBitmap* texture; static GLuint texName; //Scene Graph Node* rootNode; //Calculating fps int frame = 0, time, timebase=0; float fps=0.0f; int font=(int)GLUT_BITMAP_8_BY_13; char s[30]; +//For testing +PolyMeshNode* humveeNode; + /** Draw a 24x24 grid **/ static void grid(int scale = 1) { //Turn off lighting for grid glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); //Start drawing lines glBegin(GL_LINES); glColor3f(0.5, 0.5, 0.5); for (int x=-12; x<=12; x++){ if (x != 0){ glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(-12*scale)); glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(12*scale)); } } for (int z=-12; z<=12; z++){ if (z != 0){ glVertex3f((GLfloat)(-12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); glVertex3f((GLfloat)(12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); } } glEnd(); //Make sure the lines at the origin are nice and different + /* glBegin(GL_LINES); glColor3f(0.75, 0.75, 0.75); glVertex3f(0, 0, (GLfloat)(-12*scale)); glVertex3f(0, 0, (GLfloat)(12*scale)); glVertex3f((GLfloat)(-12*scale), 0, 0); glVertex3f((GLfloat)(12*scale), 0, 0); glEnd(); + */ + + //Draw axis + glBegin(GL_LINES); + //x axis should be red and pointing to positive x + glColor3f(1.0, 0.0, 0.0); + glVertex3f(0.0, 0.0, 0.0); + glVertex3f(12*scale, 0.0, 0.0); + glEnd(); + + //Draw cone + glPushMatrix(); + glTranslatef(12*scale, 0.0, 0.0); + glRotatef(90, 0.0, 1.0, 0.0); + glutSolidCone(0.2, 0.75, 8, 3); + glPopMatrix(); + + glBegin(GL_LINES); + //y axis + glColor3f(0.0, 1.0, 0.0); + glVertex3f(0.0, 0.0, 0.0); + glVertex3f(0.0, 12*scale, 0.0); + glEnd(); + + //Draw cone + glPushMatrix(); + glTranslatef(0.0, 12*scale, 0.0); + glRotatef(-90, 1.0, 0.0, 0.0); + glutSolidCone(0.2, 0.75, 8, 3); + glPopMatrix(); + + glBegin(GL_LINES); + //z axis + glColor3f(0.0, 0.0, 1.0); + glVertex3f(0.0, 0.0, 0.0); + glVertex3f(0.0, 0.0, 12*scale); + glEnd(); + + //Draw cone + glPushMatrix(); + glTranslatef(0.0, 0.0, 12*scale); + glutSolidCone(0.2, 0.75, 8, 3); + glPopMatrix(); glFlush(); //Turn lighting back on glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); } static void draw_models() { //Draw using scene graph rootNode->render(); } void drawText(char* string) { char* p; for (p=string; *p; p++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *p); } } /** Calculate and display FPS **/ static void profiler() { glDisable(GL_TEXTURE_2D); //Calculate FPS - frame++; - time = glutGet(GLUT_ELAPSED_TIME); - - if ((time - timebase) > 1000) { - sprintf(s,"FPS: %4.2f", frame*1000.0/(time-timebase)); - timebase = time; - frame = 0; + frame++; //Increment number of frames + time = glutGet(GLUT_ELAPSED_TIME); //Get current time + + //Time is current time, timebase is last time since we took a benchmark + if ((time - timebase) > 500) { //Do this every x milliseconds + + float fps = 1000* (float)frame / (float)(time-timebase); + sprintf(s,"FPS: %4.2f", fps ); + + timebase = time; //Set timebase to current time + frame = 0; //Reset number of frames } glColor3f(1.0f, 1.0f, 1.0f); glWindowPos2i(5, 5); drawText(s); glEnable(GL_TEXTURE_2D); } /** Display function **/ static void display() { //Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); + //Call scene graph camera + sgCamera->viewTransform(); + /** Camera setup **/ + //Translate & Rotate Polar Views + /* glTranslatef(-(GLfloat)(camera->point_of_interest->x + pan_x_change), (GLfloat)(camera->point_of_interest->y + pan_y_change), -((GLfloat)camera->distance + (GLfloat)cam_distance_change)); //Translate along the z axis away from camera glRotatef((GLfloat)camera->twist + (GLfloat)twist_change, (GLfloat)0.0, (GLfloat)0.0, (GLfloat)1.0); //Rotate around z axis (usually by 0) glRotatef((GLfloat)camera->elevation + (GLfloat)elevation_change, (GLfloat)1.0, (GLfloat)0.0, (GLfloat)0.0); //Rotate around x axis glRotatef((GLfloat)camera->azimuth + (GLfloat)azimuth_change, (GLfloat)0.0, (GLfloat)1.0, (GLfloat)0.0); //Rotate around y axis + */ //Draw grid grid(); //Wireframe switching //If shaded mode, draw the model with shading, else only draw the wireframe if (shaded_mode){ //Setup polygon offset for drawing wire on shaded glPolygonOffset(1.0, 1.0); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glColor3f(1.0, 1.0, 1.0); //Draw the obj model draw_models(); glDisable(GL_POLYGON_OFFSET_FILL); //If show wireframe, render the wireframe on top of shaded object if (show_wireframe){ glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glColor3f(0.0, 0.0, 0.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); } } else { //Wireframe only glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); glDisable(GL_CULL_FACE); glColor3f(1.0, 1.0, 1.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE); } profiler(); glutSwapBuffers(); } /** Sets the projection **/ static void set_projection() { + sgCamera->setProjection(width, height); + /* glViewport(0, 0, (GLsizei) width, (GLsizei) height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Perspective mode or ortho float aspect_ratio = (float)width / (float)height; if (camera->perspective_mode){ gluPerspective(camera->fov, GLfloat(aspect_ratio), camera->near_plane, camera->far_plane); } else { //Keep aspect ratio float left, right, bottom, top, temp_ortho_zoom; temp_ortho_zoom = camera->ortho_zoom + ortho_zoom_change; if (aspect_ratio < 1.0){ left = -temp_ortho_zoom; right = temp_ortho_zoom; bottom = -temp_ortho_zoom * ( 1.0f / aspect_ratio ); top = temp_ortho_zoom * ( 1.0f / aspect_ratio ); } else { left = -temp_ortho_zoom * aspect_ratio; right = temp_ortho_zoom * aspect_ratio; bottom = -temp_ortho_zoom; top = temp_ortho_zoom; } glOrtho(left, right, bottom, top, -camera->far_plane, camera->far_plane); } + */ } /** Reshape function **/ static void reshape(int new_width, int new_height) { //Set Global Variables width = new_width; height = new_height; set_projection(); + //sgCamera->setProjection(width, height); } /** Keyboard Input **/ static void keyboard_func(unsigned char key, int mx, int my) { switch (key) { //Camera Motion for Assignment case 'u': camera->point_of_interest->y -= 0.02f; glutPostRedisplay(); break; case 'd': camera->point_of_interest->y += 0.02f; glutPostRedisplay(); break; case 'l': camera->point_of_interest->x -= 0.02f; glutPostRedisplay(); break; case 'r': camera->point_of_interest->x += 0.02f; glutPostRedisplay(); break; case 'f': camera->distance -= 0.2f; glutPostRedisplay(); break; case 'b': camera->distance += 0.2f; glutPostRedisplay(); break; //Views case 'c': //Reset views //Destroy and reinitialize camera + /* delete camera; camera = new PolarCamera(); set_projection(); + */ break; case 'w': //Show Wireframe show_wireframe = show_wireframe == false ? true : false; break; case 's': //Shaded Model shaded_mode = shaded_mode == false ? true : false; break; case 'p': //Perspective camera->perspective_mode = true; set_projection(); break; case 'o': //Ortho camera->perspective_mode = false; set_projection(); break; case 'z': //Zoom forward if (camera->perspective_mode){ camera->fov -= 1.5f; } else { camera->ortho_zoom -= 0.1f; } set_projection(); break; case 'Z': //Zoom back if (camera->perspective_mode){ camera->fov += 1.5f; } else { camera->ortho_zoom += 0.1f; } set_projection(); break; //Alternative zoom case '+': //Zoom forward if (camera->perspective_mode){ camera->fov -= 1.5f; } else { camera->ortho_zoom -= 0.1f; } set_projection(); break; case '-': //Zoom back if (camera->perspective_mode){ camera->fov += 1.5f; } else { camera->ortho_zoom += 0.1f; } set_projection(); break; //Models case '1': model = 0; break; case '2': model = 1; break; case '3': model = 2; break; case '4': model = 3; break; case '5': model = 4; break; case '6': model = 5; break; case '7': model = 6; break; case '8': model = 7; break; //Exit case 27: exit(0); } glutPostRedisplay(); } /** Function Keys **/ static void functionKeys(int key, int mx, int my) { } /** Mouse Clicks **/ static void mouse_clicks(int button, int state, int mx, int my) { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) { left_mouse_down = true; //Set mouse down state to true mouse_down_x = mx; //Record screen position of mouse when user clicked left button mouse_down_y = my; //cout << "Left mouse button clicked at:" << mx << ", " << my << endl; } else { left_mouse_down = false; //Add changes to camera - camera->azimuth += azimuth_change; - camera->elevation += elevation_change; + sgCamera->azimuth += sgCamera->azimuth_offset; + sgCamera->elevation += sgCamera->elevation_offset; + sgCamera->azimuth_offset = 0.0f; + sgCamera->elevation_offset = 0.0f; - //Reset deltas - azimuth_change = 0; - elevation_change = 0; } break; case GLUT_RIGHT_BUTTON: //Move camera forward and back if (state == GLUT_DOWN) { right_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { right_mouse_down = false; + //Reset camera distance offset + sgCamera->distance += sgCamera->distance_offset; + sgCamera->distance_offset = 0.0f; + //Reset distance deltas camera->distance += cam_distance_change; cam_distance_change = 0; //Ortho camera->ortho_zoom += ortho_zoom_change; ortho_zoom_change = 0; } break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_DOWN) { middle_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { middle_mouse_down = false; + sgCamera->panX += sgCamera->panX_offset; sgCamera->panX_offset = 0.0f; + sgCamera->panY += sgCamera->panY_offset; sgCamera->panY_offset = 0.0f; + + //Reset panning deltas camera->point_of_interest->x += pan_x_change; camera->point_of_interest->y += pan_y_change; pan_x_change = 0; pan_y_change = 0; } break; } } /** Mouse Movement **/ static void mouse_move(int mx, int my) { //Only bother processing if mouse button is pressed //Left Mouse Button - Orbit if (left_mouse_down){ - azimuth_change = - (float(mouse_down_x) - float(mx)) / float(width) * 90; - elevation_change = - (float(mouse_down_y) - float(my)) / float(height) * 90; + + sgCamera->azimuth_offset = -(float(mouse_down_x) - float(mx)) / float(width) * 90; + sgCamera->elevation_offset = -(float(mouse_down_y) - float(my)) / float(height) * 90; + } //Right Mouse Button - Dolly if (right_mouse_down){ + if (sgCamera->perspectiveMode) + { + sgCamera->distance_offset = (float(mouse_down_x) - float(mx)) / float(width) * 10; + } else { + sgCamera->distance_offset = (float(mouse_down_x) - float(mx)) / float(width); + sgCamera->setProjection(width, height); + } + if (camera->perspective_mode){ cam_distance_change = (float(mouse_down_x) - float(mx)) / float(width) * 10; } else { ortho_zoom_change = (float(mouse_down_x) - float(mx)) / float(width); set_projection(); } } //Middle Mouse Button - Panning if (middle_mouse_down){ - pan_x_change = (float(mouse_down_x) - float(mx)) / float(width) * 5; - pan_y_change = (float(mouse_down_y) - float(my)) / float(height) * 5; + sgCamera->panX_offset = (float(mouse_down_x) - float(mx)) / float(width) * 5; + sgCamera->panY_offset = -(float(mouse_down_y) - float(my)) / float(height) * 5; } //Force redisplay if (left_mouse_down || middle_mouse_down || right_mouse_down){ glutPostRedisplay(); } } /** Enable lighting & materials **/ static void lighting() { glShadeModel(GL_SMOOTH); //glShadeModel(GL_FLAT); //Setup Material GLfloat mat_ambient[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_diffuse[] = {(GLfloat)0.9, (GLfloat)0.9, (GLfloat)0.9, (GLfloat)1.0}; GLfloat mat_specular[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_shininess[] = {(GLfloat)50}; glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); //Setup Light(s) GLfloat light_position[] = {30.0, 30.0, 30.0, 0.0}; GLfloat white_light[] = {1.0, 1.0, 1.0, 1.0}; glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light); glLightfv(GL_LIGHT0, GL_SPECULAR, white_light); //Setup Ambient Light //GLfloat lmodel_ambient[] = {(GLfloat)0.2, (GLfloat)0.2, (GLfloat)0.2, (GLfloat)1.0}; //Turn on lighting glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); } - - -/** -Do this while idle -Calculate fps -**/ -static void idleFunc() -{ - - - -} - - /** Clear out the screen **/ static void init() { - + //Backface culling + glEnable(GL_CULL_FACE); + glEnable(GL_TEXTURE_2D); + + glClearColor(0.0, 0.0, 0.0, 0.0); + //Load models /* uhtiger = new OBJModel("models/uhtiger.obj"); PolyMeshNode* uhTigerNode = new PolyMeshNode(); uhTigerNode->attachModel(uhtiger); Texture* uhTigerTexture = new Texture("textures/uhtiger.bmp"); uhTigerNode->attachTexture(uhTigerTexture); uhTigerNode->translate->z = 5.0f; - */ m1abrams = new OBJModel("models/m1abrams.obj"); PolyMeshNode* m1AbramsNode = new PolyMeshNode(); m1AbramsNode->attachModel(m1abrams); Texture* m1AbramsTexture = new Texture("textures/M1_ABRAM.bmp"); m1AbramsNode->attachTexture(m1AbramsTexture); m1AbramsNode->translate->z = -5.0f; m1AbramsNode->translate->x = -15.0f; + */ - /* - humveehardtop = new OBJModel("models/humveehardtop.obj"); - PolyMeshNode* humveeNode = new PolyMeshNode(); + OBJModel* humveehardtop = new OBJModel("models/humveehardtop.obj"); + humveeNode = new PolyMeshNode(); humveeNode->attachModel(humveehardtop); Texture* humveeTexture = new Texture("textures/humveehardtop.bmp"); humveeNode->attachTexture(humveeTexture); - humveeNode->translate->z = -5.0f; - humveeNode->translate->x = 15.0f; - */ - + humveeNode->rotate->y = -90; + + PolyMeshNode* humveeNode2 = new PolyMeshNode(); + humveeNode2->attachModel(humveehardtop); + humveeNode2->attachTexture(humveeTexture); + humveeNode2->translate->x = -20; + humveeNode2->rotate->y = 90; + + PolyMeshNode* humveeNode3 = new PolyMeshNode(); + humveeNode3->attachModel(humveehardtop); + humveeNode3->attachTexture(humveeTexture); + humveeNode3->translate->x = -20; + //Scene Graph rootNode = new Node(); - /* - TransformNode* translatetest1 = new TransformNode(ROTATE); - translatetest1->rotate->y = 45; - rootNode->addChild(translatetest1); - translatetest1->addChild(uhTigerNode); - translatetest1->addChild(m1AbramsNode); - translatetest1->addChild(humveeNode); - */ + rootNode->addChild(humveeNode); + humveeNode->addChild(humveeNode2); + humveeNode2->addChild(humveeNode3); //10 tanks + /* for (int x=-10; x<=10; x++) { for (int z=-10; z<=10; z++) { TransformNode* transform = new TransformNode(TRANSLATE); transform->translate->x = x*20; transform->translate->z = z*20; transform->addChild(m1AbramsNode); rootNode->addChild(transform); } } + */ - glClearColor(0.0, 0.0, 0.0, 0.0); + //Create a camera and attach to root node + sgCamera = new CameraNode(FIRSTPERSON); + sgCamera->translate->x = -10.0f; + sgCamera->translate->z = 10.0f; + sgCamera->translate->y = 2.0f; + sgCamera->rotate->y = 45; + //rootNode->addChild(sgCamera); + + sgCamera = new CameraNode(POLAR); + sgCamera->distance = 30.0f; + sgCamera->azimuth = -180.0f; + sgCamera->elevation = 40.0f; + humveeNode3->addChild(sgCamera); //Set up lighting lighting(); //Anti-Aliasing /* glEnable (GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glLineWidth (1); */ - //Backface culling - glEnable(GL_CULL_FACE); - glEnable(GL_TEXTURE_2D); } /** Main function **/ int main(int argc, char** argv) { //Get current directory cout << "Firing up OBJViewer" << endl; cout << "===================" << endl << endl; cout << "Camera Motion " << endl; cout << "Orbit: Left click and drag mouse" << endl; cout << "Panning: Middle click and drag mouse" << endl; cout << "Dolly: Right click and drag mouse" << endl << endl; cout << "Viewport Controls " << endl; cout << "w: Toggle wireframe" << endl; cout << "s: Toggle shaded mode" << endl; cout << "p: Perspective mode" << endl; cout << "o: Orthographic mode" << endl; cout << "+ or z: Zoom in" << endl; cout << "- or Z(shift-z): Zoom out" << endl; cout << "c: Reset view" << endl << endl; cout << "Escape: Quit" << endl; glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 100); glutCreateWindow("OBJViewer Test - Leonard Teo"); //Initialize GLEW GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); exit(1); } fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard_func); glutSpecialFunc(functionKeys); glutMouseFunc(mouse_clicks); glutMotionFunc(mouse_move); glutIdleFunc(display); //Set idle function to force refresh glutMainLoop(); //Cleanup delete camera; exit(0); } \ No newline at end of file diff --git a/PolyMeshNode.cpp b/PolyMeshNode.cpp index b63ef75..918922f 100644 --- a/PolyMeshNode.cpp +++ b/PolyMeshNode.cpp @@ -1,166 +1,180 @@ /* * PolyMesh.cpp * OBJViewer * * Created by Leonard Teo on 10-10-05. * */ #include "PolyMeshNode.h" //Constructor -PolyMeshNode::PolyMeshNode() +PolyMeshNode::PolyMeshNode() : Node() { this->mesh = NULL; this->texture = NULL; } //Destructor PolyMeshNode::~PolyMeshNode() { delete this->mesh; delete this->texture; delete this; } //attachModel void PolyMeshNode::attachModel(OBJModel* model) { this->mesh = model; } //attachTexture void PolyMeshNode::attachTexture(Texture* texture) { this->texture = texture; } void PolyMeshNode::draw() { //Load texture if (this->texture != NULL) { glBindTexture(GL_TEXTURE_2D, this->texture->textureID); } //Check vertex buffer object extension if (glewGetExtension("GL_ARB_vertex_buffer_object")) { //Load vertices glBindBuffer(GL_ARRAY_BUFFER, this->mesh->vbo_vertices); glVertexPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0)); glEnableClientState(GL_VERTEX_ARRAY); //Load normals glBindBuffer(GL_ARRAY_BUFFER, this->mesh->vbo_normals); glNormalPointer(GL_FLOAT, 0, BUFFER_OFFSET(0)); glEnableClientState(GL_NORMAL_ARRAY); //Load UVs glBindBuffer(GL_ARRAY_BUFFER, this->mesh->vbo_uvs); glTexCoordPointer(2, GL_FLOAT, 0, BUFFER_OFFSET(0)); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->mesh->vbo_index); glDrawElements(GL_TRIANGLES, 3*this->mesh->numFaces, GL_UNSIGNED_INT, BUFFER_OFFSET(0)); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } else { //Drawing with vertex arrays glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointer(3, GL_FLOAT, 0, this->mesh->vertexArray); glNormalPointer(GL_FLOAT, 0, this->mesh->normalsArray); glTexCoordPointer(2, GL_FLOAT, 0, this->mesh->uvArray); glDrawElements(GL_TRIANGLES, 3*this->mesh->numFaces, GL_UNSIGNED_INT, this->mesh->indexArray); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } /* //Old immediate mode drawing code glBegin(GL_TRIANGLES); for (int face = 0; face < this->numFaces; face++) { //Draw the vertex at each of the vertex numbders glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][0]]->u, (GLfloat)this->uvs[this->uvIndex[face][0]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][0]]->x, (GLfloat)this->normals[this->normalsIndex[face][0]]->y, (GLfloat)this->normals[this->normalsIndex[face][0]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][0]]->x, (GLfloat)this->vertices[this->index[face][0]]->y, (GLfloat)this->vertices[this->index[face][0]]->z); glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][1]]->u, (GLfloat)this->uvs[this->uvIndex[face][1]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][1]]->x, (GLfloat)this->normals[this->normalsIndex[face][1]]->y, (GLfloat)this->normals[this->normalsIndex[face][1]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][1]]->x, (GLfloat)this->vertices[this->index[face][1]]->y, (GLfloat)this->vertices[this->index[face][1]]->z); glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][2]]->u, (GLfloat)this->uvs[this->uvIndex[face][2]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][2]]->x, (GLfloat)this->normals[this->normalsIndex[face][2]]->y, (GLfloat)this->normals[this->normalsIndex[face][2]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][2]]->x, (GLfloat)this->vertices[this->index[face][2]]->y, (GLfloat)this->vertices[this->index[face][2]]->z); /* Non-Optimized code for debugging //Get vertex numbers int v1, v2, v3; v1 = this->index[face][0]; v2 = this->index[face][1]; v3 = this->index[face][2]; //Get Normal numbers int n1, n2, n3; n1 = this->normalsIndex[face][0]; n2 = this->normalsIndex[face][1]; n3 = this->normalsIndex[face][2]; //Get UVs int uv1, uv2, uv3; uv1 = this->uvIndex[face][0]; uv2 = this->uvIndex[face][1]; uv3 = this->uvIndex[face][2]; //Draw the vertex at each of the vertex numbders glTexCoord2f((GLfloat)this->uvs[uv1]->u, (GLfloat)this->uvs[uv1]->v); glNormal3f((GLfloat)this->normals[n1]->x, (GLfloat)this->normals[n1]->y, (GLfloat)this->normals[n1]->z); glVertex3f((GLfloat)this->vertices[v1]->x, (GLfloat)this->vertices[v1]->y, (GLfloat)this->vertices[v1]->z); glTexCoord2f((GLfloat)this->uvs[uv2]->u, (GLfloat)this->uvs[uv2]->v); glNormal3f((GLfloat)this->normals[n2]->x, (GLfloat)this->normals[n2]->y, (GLfloat)this->normals[n2]->z); glVertex3f((GLfloat)this->vertices[v2]->x, (GLfloat)this->vertices[v2]->y, (GLfloat)this->vertices[v2]->z); glTexCoord2f((GLfloat)this->uvs[uv3]->u, (GLfloat)this->uvs[uv3]->v); glNormal3f((GLfloat)this->normals[n3]->x, (GLfloat)this->normals[n3]->y, (GLfloat)this->normals[n3]->z); glVertex3f((GLfloat)this->vertices[v3]->x, (GLfloat)this->vertices[v3]->y, (GLfloat)this->vertices[v3]->z); */ /* } glEnd(); */ } void PolyMeshNode::render() { - for (int i=0; i < this->children->size(); i++) - { - this->children->at(i)->render(); - } + //Draw this glPushMatrix(); glTranslatef((GLfloat)this->translate->x, (GLfloat)this->translate->y, (GLfloat)this->translate->z); + + //This piece of code is not good because the order of rotation is actually important. + //We need to figure out a way to rotate an entire local coordinate system. + //This should be relatively simple but we'll need to figure it out... + glRotatef((GLfloat)this->rotate->z, (GLfloat)0.0f, (GLfloat)0.0f, (GLfloat)1.0f); + glRotatef((GLfloat)this->rotate->y, (GLfloat)0.0f, (GLfloat)1.0f, (GLfloat)0.0f); + glRotatef((GLfloat)this->rotate->x, (GLfloat)1.0f, (GLfloat)0.0f, (GLfloat)0.0f); + + glScalef((GLfloat)this->scale->x, (GLfloat)this->scale->y, (GLfloat)this->scale->z); + this->draw(); + + //Draw children + for (int i=0; i < this->children->size(); i++) + { + this->children->at(i)->render(); + } + glPopMatrix(); } \ No newline at end of file diff --git a/Vector3.h b/Vector3.h index 9edade6..009cfde 100644 --- a/Vector3.h +++ b/Vector3.h @@ -1,30 +1,32 @@ /** Vector3 class Simple storage for Vector3 type Will expand later when I figure out something useful to do with this. @author Leonard Teo **/ #ifndef VECTOR3_H #define VECTOR3_H #include <iostream> class Vector3 { public: float x, y, z; Vector3(void); Vector3(float nx, float ny, float nz); ~Vector3(void); + + //Overload the << operator for easily debugging values friend std::ostream& operator<<(std::ostream& output, const Vector3* v); }; #endif
leonardteo/OBJViewer
10037dd8f40fdcada664b77cc54d9cb7a5d393b3
Got vertex array drawing working
diff --git a/Camera.cpp b/CameraNode.cpp similarity index 70% rename from Camera.cpp rename to CameraNode.cpp index 2d2bc86..4b6021b 100644 --- a/Camera.cpp +++ b/CameraNode.cpp @@ -1,20 +1,20 @@ /* * Camera.cpp * OBJViewer * * Created by Leonard Teo on 10-10-06. * Copyright 2010 Leonard Teo. All rights reserved. * */ -#include "Camera.h" +#include "CameraNode.h" -Camera::Camera() +CameraNode::CameraNode() { //Set node type this->type = CAMERA; } -Camera::~Camera() +CameraNode::~CameraNode() { } \ No newline at end of file diff --git a/Camera.h b/CameraNode.h similarity index 79% rename from Camera.h rename to CameraNode.h index e6ea30f..d55a64c 100644 --- a/Camera.h +++ b/CameraNode.h @@ -1,42 +1,42 @@ /* * Camera.h * OBJViewer * * Created by Leonard Teo on 10-10-06. * Copyright 2010 Leonard Teo. All rights reserved. * */ -#ifndef CAMERA_H -#define CAMERA_H +#ifndef CAMERANODE_H +#define CAMERANODE_H #include "Node.h" enum CameraProjection { PERSPECTIVE, ORTHO }; enum CameraType { POLAR, FIRSTPERSON }; /** * Camera class extends Node */ -class Camera : public Node +class CameraNode : public Node { public: //Data Members CameraProjection cameraProjection; CameraType cameraType; //Constructor/Destructor - Camera(); - ~Camera(); + CameraNode(); + ~CameraNode(); }; #endif diff --git a/OBJModel.cpp b/OBJModel.cpp index 48a4a3e..04aa00d 100644 --- a/OBJModel.cpp +++ b/OBJModel.cpp @@ -1,346 +1,474 @@ #include "OBJModel.h" using namespace std; //Constructor OBJModel::OBJModel(const char* fileName) { this->init(); this->load(fileName); } //Free memory OBJModel::~OBJModel(void) { //Free all vertices and normals - for (int i=0; i<this->numVertices; i++) - { - delete this->vertices[i]; - } - delete this->vertices; + delete [] this->vertices; + delete [] this->normals; + delete [] this->uvs; - for (int i=0; i<this->numNormals; i++) - { - delete this->normals[i]; - } - delete this->normals; - - for (int i=0; i<this->numUVs; i++) - { - delete this->uvs[i]; - } - delete this->uvs; - - delete this->index; - delete this->normalsIndex; - delete this->uvIndex; + delete [] this->index; + delete [] this->normalsIndex; + delete [] this->uvIndex; + + delete [] this->vertexArray; + delete [] this->normalsArray; + delete [] this->uvArray; + delete [] this->indexArray; } //General class initialization void OBJModel::init() { + //Set node type + this->type = POLYMESH; + this->hasTexture = false; + this->numVertices = 0; this->numFaces = 0; this->numUVs = 0; - this->numNormals = 0; + + //Set all arrays to null this->vertices = NULL; this->uvs = NULL; - this->index = NULL; this->normals = NULL; + this->index = NULL; this->uvIndex = NULL; - - this->type = POLYMESH; - this->hasTexture = false; + this->normalsIndex = NULL; + this->vertexArray = NULL; + this->normalsArray = NULL; + this->uvArray = NULL; + this->indexArray = NULL; } +/** +* Load the OBJ Model into memory +**/ + void OBJModel::load(const char* fileName) { char buffer[255]; //Open file for reading ifstream file; file.open(fileName); if (!file.is_open()) { //If file isn't open cout << "Error loading file: " << fileName << endl; return; } else { //First pass of reading the file counts the data while ( !file.eof() ){ //Read the line file.getline(buffer, 255); //Read the line switch(buffer[0]) { //Vertex case 'v': switch(buffer[1]) { case ' ': this->numVertices++; break; case 'n': this->numNormals++; break; case 't': this->numUVs++; break; } break; //Face case 'f': this->numFaces++; break; default: break; } } //end of file //Echo the stats printf("fileName: %s \n", fileName); printf("Vertices: %d \n", this->numVertices); printf("Vertex Normals: %d \n", this->numNormals); printf("Faces: %d \n", this->numFaces); printf("\n"); //Allocate memory for data //Init vertices this->vertices = new Vector3*[this->numVertices]; - this->index = new int*[this->numFaces]; //Triangles now + this->index = new int*[this->numFaces]; //Init normals this->normals = new Vector3*[this->numNormals]; this->normalsIndex = new int*[this->numFaces]; //Triangles //Init UV's this->uvs = new UV*[this->numUVs]; this->uvIndex = new int*[this->numFaces]; //Initialize each of the indices for (int i=0; i<this->numFaces; i++){ this->index[i] = new int[3]; this->normalsIndex[i] = new int[3]; this->uvIndex[i] = new int[3]; for (int j=0; j<3; j++){ this->index[i][j] = 0; this->normalsIndex[i][j] = 0; this->uvIndex[i][j] = 0; } } //Second pass of file to load data file.clear(); //Clear eof status file.seekg(0, ios::beg); //Move cursor to beginning int currentVertex = 0; int currentIndex = 0; int currentNormal = 0; int currentUV = 0; int currentUVIndex = 0; int currentNormalIndex = 0; while (!file.eof()){ //Read line file.getline(buffer, 255); switch (buffer[0]){ //Vertex case 'v': switch(buffer[1]){ case ' ': //Create new vertex this->vertices[currentVertex] = new Vector3(); sscanf(buffer, "v %f %f %f", &this->vertices[currentVertex]->x, &this->vertices[currentVertex]->y, &this->vertices[currentVertex]->z); currentVertex++; break; case 'n': //Create new vertex normal this->normals[currentNormal] = new Vector3(); sscanf(buffer, "vn %f %f %f", &this->normals[currentNormal]->x, &this->normals[currentNormal]->y, &this->normals[currentNormal]->z); currentNormal++; break; case 't': //Create new UV this->uvs[currentUV] = new UV(); sscanf(buffer, "vt %f %f", &this->uvs[currentUV]->u, &this->uvs[currentUV]->v); currentUV++; break; } break; case 'f': - //sscanf(buffer, "f %d/%*d/%d %d/%*d/%d %d/%*d/%d", &this->index[currentIndex][0], &this->normalsIndex[currentNormalIndex][0], &this->index[currentIndex][1], &this->normalsIndex[currentNormalIndex][1], &this->index[currentIndex][2], &this->normalsIndex[currentNormalIndex][2]); sscanf(buffer, "f %d/%d/%d %d/%d/%d %d/%d/%d", &this->index[currentIndex][0], &this->uvIndex[currentUVIndex][0], &this->normalsIndex[currentNormalIndex][0], &this->index[currentIndex][1], &this->uvIndex[currentUVIndex][1], &this->normalsIndex[currentNormalIndex][1], &this->index[currentIndex][2], &this->uvIndex[currentUVIndex][2], &this->normalsIndex[currentNormalIndex][2]); currentIndex++; currentNormalIndex++; currentUVIndex++; break; } } //end of file //Release file pointer file.close(); } - - //Debug - echo out all the vertices and faces - /* - printf("Vertices: \n"); - for(int i=0; i< this->numVertices; i++) + //decrement all indices to cater for OpenGL (OBJ indices start at 1) + for(int i = 0; i < this->numFaces; i++) { - printf(" %f %f %f \n", this->vertices[i]->x, this->vertices[i]->y, this->vertices[i]->z ); + for(int j=0; j<3; j++){ + this->index[i][j]--; + this->normalsIndex[i][j]--; + this->uvIndex[i][j]--; + } } - printf("\n\nUV coordinates: \n"); - for (int i=0; i< this->numUVs; i++) + //Prepare the arrays for drawing + this->prepArrays(); + +} + +/** +Takes the vertex, normals and texture coords and turns them into straight march arrays for OpenGL to render +**/ +void OBJModel::prepArrays() +{ + + //Initialize the arrays + this->vertexArray = new GLfloat[this->numFaces *3 * 3]; //3 vertices to a face, 3 floats to a vertex + this->normalsArray = new GLfloat[this->numFaces *3 * 3]; + this->indexArray = new GLuint[this->numFaces * 3]; + this->uvArray = new GLfloat[this->numFaces * 3 * 2]; //3 vertices to a face, 2 floats to a UV + + //Turn index into a straight march + int numElements = this->numFaces * 3; + for (int i=0; i<numElements; i++) { - printf(" %f %f \n", this->uvs[i]->u, this->uvs[i]->v); + this->indexArray[i] = i; } - printf("\n\nVertex Normals: \n"); - for(int i=0; i< this->numNormals ; i++) + //Figure out vertices, normals and UVs + for (int face = 0; face < this->numFaces; face++) { - printf(" %f %f %f \n", this->normals[i]->x, this->normals[i]->y, this->normals[i]->z); + + //Get vertex numbers + int v1, v2, v3; + v1 = this->index[face][0]; + v2 = this->index[face][1]; + v3 = this->index[face][2]; + + //Get Normal numbers + int n1, n2, n3; + n1 = this->normalsIndex[face][0]; + n2 = this->normalsIndex[face][1]; + n3 = this->normalsIndex[face][2]; + + //Get UVs + int uv1, uv2, uv3; + uv1 = this->uvIndex[face][0]; + uv2 = this->uvIndex[face][1]; + uv3 = this->uvIndex[face][2]; + + //Element 1 + this->uvArray[6*face] = (GLfloat) this->uvs[uv1]->u; + this->uvArray[6*face + 1] = (GLfloat) this->uvs[uv1]->v; + + this->normalsArray[9*face] = (GLfloat) this->normals[n1]->x; + this->normalsArray[9*face + 1] = (GLfloat) this->normals[n1]->y; + this->normalsArray[9*face + 2] = (GLfloat) this->normals[n1]->z; + + this->vertexArray[9*face] = (GLfloat) this->vertices[v1]->x; + this->vertexArray[9*face + 1] = (GLfloat) this->vertices[v1]->y; + this->vertexArray[9*face + 2] = (GLfloat) this->vertices[v1]->z; + + //Element 2 + this->uvArray[6*face + 2] = (GLfloat) this->uvs[uv2]->u; + this->uvArray[6*face + 3] = (GLfloat) this->uvs[uv2]->v; + + this->normalsArray[9*face + 3] = (GLfloat) this->normals[n2]->x; + this->normalsArray[9*face + 4] = (GLfloat) this->normals[n2]->y; + this->normalsArray[9*face + 5] = (GLfloat) this->normals[n2]->z; + + this->vertexArray[9*face + 3] = (GLfloat) this->vertices[v2]->x; + this->vertexArray[9*face + 4] = (GLfloat) this->vertices[v2]->y; + this->vertexArray[9*face + 5] = (GLfloat) this->vertices[v2]->z; + + //Element 3 + this->uvArray[6*face + 4] = (GLfloat) this->uvs[uv3]->u; + this->uvArray[6*face + 5] = (GLfloat) this->uvs[uv3]->v; + + this->normalsArray[9*face + 6] = (GLfloat)this->normals[n3]->x; + this->normalsArray[9*face + 7] = (GLfloat)this->normals[n3]->y; + this->normalsArray[9*face + 8] = (GLfloat)this->normals[n3]->z; + + this->vertexArray[9*face + 6] = (GLfloat)this->vertices[v3]->x; + this->vertexArray[9*face + 7] = (GLfloat)this->vertices[v3]->y; + this->vertexArray[9*face + 8] = (GLfloat)this->vertices[v3]->z; } + + //Release all the object memory - we only need the arrays + delete [] this->vertices; + delete [] this->normals; + delete [] this->uvs; + delete [] this->index; + delete [] this->normalsIndex; + delete [] this->uvIndex; + + //this->debugArrays(); +} - printf("\n\nIndex/UV/Normal: \n"); - for(int i=0; i< this->numFaces; i++){ - printf(" %d/%d/%d %d/%d/%d %d/%d/%d\n", this->index[i][0], this->uvIndex[i][0], this->normalsIndex[i][0], this->index[i][1], this->uvIndex[i][1], this->normalsIndex[i][1], this->index[i][2], this->uvIndex[i][2], this->normalsIndex[i][2]); +//Show all the array data +void OBJModel::debugArrays() +{ + FILE *file = fopen("debug.txt", "w"); + if (file == NULL) + { + printf("Couldn't open debug file."); + return; } - */ + fprintf(file, "Element Index: \n"); + for (int face=0; face < this->numFaces; face++) + { + fprintf(file, "%d %d %d \n", this->indexArray[3*face], this->indexArray[3*face + 1], this->indexArray[3*face + 2]); + } - //decrement all indices to cater for OpenGL (OBJ indices start at 1) - for(int i = 0; i < this->numFaces; i++) + fprintf(file, "\nVertices: \n"); + for (int face=0; face < this->numFaces; face++) { - for(int j=0; j<3; j++){ - this->index[i][j]--; - this->normalsIndex[i][j]--; - this->uvIndex[i][j]--; - } + fprintf(file, "%f %f %f %f %f %f %f %f %f \n", + this->vertexArray[3*face], this->vertexArray[3*face + 1], this->vertexArray[3*face + 2], + this->vertexArray[3*face+3], this->vertexArray[3*face + 4], this->vertexArray[3*face + 5], + this->vertexArray[3*face+6], this->vertexArray[3*face + 7], this->vertexArray[3*face + 8] + ); } + fprintf(file, "\nNormals: \n"); + for (int face=0; face < this->numFaces; face++) + { + fprintf(file, "%f %f %f %f %f %f %f %f %f \n", + this->normalsArray[3*face], this->normalsArray[3*face + 1], this->normalsArray[3*face + 2], + this->normalsArray[3*face+3], this->normalsArray[3*face + 4], this->normalsArray[3*face + 5], + this->normalsArray[3*face+6], this->normalsArray[3*face + 7], this->normalsArray[3*face + 8] + ); + } + fclose(file); } +/** +Overloaded scene graph render routine +**/ void OBJModel::render() { - for (int i=0; i<this->children->size(); i++) + for (int i=0; i < this->children->size(); i++) { this->children->at(i)->render(); } //Draw this glPushMatrix(); glTranslatef((GLfloat)this->translate->x, (GLfloat)this->translate->y, (GLfloat)this->translate->z); this->draw(); glPopMatrix(); } /** Drawing routine **/ void OBJModel::draw() { //Load texture if (this->hasTexture) { glBindTexture(GL_TEXTURE_2D, this->texture); } + //Drawing with vertex arrays + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_NORMAL_ARRAY); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + + glVertexPointer(3, GL_FLOAT, 0, this->vertexArray); + glNormalPointer(GL_FLOAT, 0, this->normalsArray); + glTexCoordPointer(2, GL_FLOAT, 0, this->uvArray); + + glDrawElements(GL_TRIANGLES, 3*this->numFaces, GL_UNSIGNED_INT, this->indexArray); + + glDisableClientState(GL_VERTEX_ARRAY); + glDisableClientState(GL_NORMAL_ARRAY); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + //For each face, draw a Triangle + + /* + + //Old immediate mode drawing code + glBegin(GL_TRIANGLES); for (int face = 0; face < this->numFaces; face++) { //Draw the vertex at each of the vertex numbders glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][0]]->u, (GLfloat)this->uvs[this->uvIndex[face][0]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][0]]->x, (GLfloat)this->normals[this->normalsIndex[face][0]]->y, (GLfloat)this->normals[this->normalsIndex[face][0]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][0]]->x, (GLfloat)this->vertices[this->index[face][0]]->y, (GLfloat)this->vertices[this->index[face][0]]->z); glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][1]]->u, (GLfloat)this->uvs[this->uvIndex[face][1]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][1]]->x, (GLfloat)this->normals[this->normalsIndex[face][1]]->y, (GLfloat)this->normals[this->normalsIndex[face][1]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][1]]->x, (GLfloat)this->vertices[this->index[face][1]]->y, (GLfloat)this->vertices[this->index[face][1]]->z); glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][2]]->u, (GLfloat)this->uvs[this->uvIndex[face][2]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][2]]->x, (GLfloat)this->normals[this->normalsIndex[face][2]]->y, (GLfloat)this->normals[this->normalsIndex[face][2]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][2]]->x, (GLfloat)this->vertices[this->index[face][2]]->y, (GLfloat)this->vertices[this->index[face][2]]->z); /* Non-Optimized code for debugging //Get vertex numbers int v1, v2, v3; v1 = this->index[face][0]; v2 = this->index[face][1]; v3 = this->index[face][2]; //Get Normal numbers int n1, n2, n3; n1 = this->normalsIndex[face][0]; n2 = this->normalsIndex[face][1]; n3 = this->normalsIndex[face][2]; //Get UVs int uv1, uv2, uv3; uv1 = this->uvIndex[face][0]; uv2 = this->uvIndex[face][1]; uv3 = this->uvIndex[face][2]; //Draw the vertex at each of the vertex numbders glTexCoord2f((GLfloat)this->uvs[uv1]->u, (GLfloat)this->uvs[uv1]->v); glNormal3f((GLfloat)this->normals[n1]->x, (GLfloat)this->normals[n1]->y, (GLfloat)this->normals[n1]->z); glVertex3f((GLfloat)this->vertices[v1]->x, (GLfloat)this->vertices[v1]->y, (GLfloat)this->vertices[v1]->z); glTexCoord2f((GLfloat)this->uvs[uv2]->u, (GLfloat)this->uvs[uv2]->v); glNormal3f((GLfloat)this->normals[n2]->x, (GLfloat)this->normals[n2]->y, (GLfloat)this->normals[n2]->z); glVertex3f((GLfloat)this->vertices[v2]->x, (GLfloat)this->vertices[v2]->y, (GLfloat)this->vertices[v2]->z); glTexCoord2f((GLfloat)this->uvs[uv3]->u, (GLfloat)this->uvs[uv3]->v); glNormal3f((GLfloat)this->normals[n3]->x, (GLfloat)this->normals[n3]->y, (GLfloat)this->normals[n3]->z); glVertex3f((GLfloat)this->vertices[v3]->x, (GLfloat)this->vertices[v3]->y, (GLfloat)this->vertices[v3]->z); */ - + /* } glEnd(); + */ + glFlush(); } /*** Load Texture ***/ void OBJModel::loadTexture(const char* fileName) { this->image = new MyBitmap(fileName); if (!image->loaded){ cout << "Could not load texture." << endl; exit(0); } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &this->texture); //Allocate Texture Name glBindTexture(GL_TEXTURE_2D, this->texture); //Select current texture glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->image->width, this->image->height, 0, GL_RGB, GL_UNSIGNED_BYTE, this->image->data); this->hasTexture = true; glEnable(GL_TEXTURE_2D); delete image; } \ No newline at end of file diff --git a/OBJModel.h b/OBJModel.h index 6c9e549..a95e2e1 100644 --- a/OBJModel.h +++ b/OBJModel.h @@ -1,96 +1,105 @@ /** My attempt at an OBJ parser Leonard Teo Done: Only supports triangles - remember to triangulate all models To DO: - Generate normals if a model doesn't have them - Handle groups and materials **/ #ifndef OBJMODEL_H #define OBJMODEL_H #include <iostream> #include <fstream> #include <stdio.h> #include <string> #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/GLUT.h> #else #include <GL/glut.h> #endif #include "Vector3.h" #include "MyBitmap.h" #include "Node.h" #include <vector> using namespace std; struct UV { float u; float v; }; class OBJModel: public Node { public: //Constructor OBJModel(const char* fileName); //Destructor ~OBJModel(void); //Load Texture void loadTexture(const char* fileName); //Draw the polygons using OpenGL calls void draw(); void drawArray(); //Scene graph rendering call void render(); //Generate normals - TO DO void generateNormals(); private: //Private data members //Total number of vertices int numVertices; int numFaces; int numUVs; int numNormals; bool hasTexture; //Data Vector3** vertices; Vector3** normals; UV** uvs; int** index; //2 dimensional arrays: Note these are pointers so that we can do this: this->normals_index[i][j] int** normalsIndex; int** uvIndex; - + + GLfloat* vertexArray; + GLfloat* normalsArray; + GLfloat* uvArray; + + GLuint* indexArray; //Straight line array + //Texture map MyBitmap* image; GLuint texture; //Initialize the arrays and variables void init(); //Load a model file void load(const char* fileName); + //Prepare arrays + void prepArrays(); + void debugArrays(); }; #endif \ No newline at end of file diff --git a/OBJViewer.cpp b/OBJViewer.cpp index b3b517e..6e3f477 100644 --- a/OBJViewer.cpp +++ b/OBJViewer.cpp @@ -1,703 +1,681 @@ /** OBJ Viewer **/ #include <iostream> #include <string> #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/GLUT.h> #else #include <GL/glut.h> #endif #include "PolarCamera.h" #include "OBJModel.h" #include "MyBitmap.h" #include "Node.h" -#include "Transform.h" +#include "TransformNode.h" using namespace std; //Default Screen Size const int WIDTH = 640; const int HEIGHT = 480; /** Global Variables **/ //Temporary screen width and height int width = WIDTH; int height = HEIGHT; //Mouse position int mouse_x; int mouse_y; int mouse_down_x; //Mouse position when a user clicks int mouse_down_y; //Mouse clicks states bool left_mouse_down = false; bool middle_mouse_down = false; bool right_mouse_down = false; //Model type int model = 0; //Show Wireframe bool show_wireframe = false; bool shaded_mode = true; //Camera - Polar view PolarCamera* camera = new PolarCamera(); //Temporary variables to facilitate Polar camera float azimuth_change = 0; float twist_change = 0; float elevation_change = 0; float cam_distance_change = 0.0; //Panning temporary variables float pan_x_down = 0; //When the pan button is pushed, record this float pan_y_down = 0; float pan_z_down = 0; float pan_x_change = 0; float pan_y_change = 0; //Orthographic zooming temporary variable float ortho_zoom_change = 0; //OBJ Models //OBJModel* objmodel; //Any objmodel for testing OBJModel* m1abrams; OBJModel* humveehardtop; OBJModel* uhtiger; //Texture MyBitmap* texture; static GLuint texName; //Scene Graph Node* rootNode; /** Draw a 24x24 grid **/ static void grid(int scale = 1) { //Turn off lighting for grid glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); //Start drawing lines glBegin(GL_LINES); glColor3f(0.5, 0.5, 0.5); for (int x=-12; x<=12; x++){ if (x != 0){ glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(-12*scale)); glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(12*scale)); } } for (int z=-12; z<=12; z++){ if (z != 0){ glVertex3f((GLfloat)(-12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); glVertex3f((GLfloat)(12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); } } glEnd(); //Make sure the lines at the origin are nice and different glBegin(GL_LINES); glColor3f(0.75, 0.75, 0.75); glVertex3f(0, 0, (GLfloat)(-12*scale)); glVertex3f(0, 0, (GLfloat)(12*scale)); glVertex3f((GLfloat)(-12*scale), 0, 0); glVertex3f((GLfloat)(12*scale), 0, 0); glEnd(); glFlush(); //Turn lighting back on glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); } static void draw_models() { //Draw using scene graph rootNode->render(); - //Draw all three models (let's be awesome) - /* - glPushMatrix(); - glTranslatef(-15, 0, 0); - m1abrams->draw(); - glPopMatrix(); - - uhtiger->draw(); - - glPushMatrix(); - glTranslatef(15,0,0); - humveehardtop->draw(); - glPopMatrix(); - */ - - //Switch model - /* - switch (model) - { - case 0: - m1abrams->draw(); - break; - case 1: - humveehardtop->draw(); - break; - case 2: - uhtiger->draw(); - break; - } - */ } /** Display function **/ static void display() { //Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); /** Camera setup **/ //Translate & Rotate Polar Views glTranslatef(-(GLfloat)(camera->point_of_interest->x + pan_x_change), (GLfloat)(camera->point_of_interest->y + pan_y_change), -((GLfloat)camera->distance + (GLfloat)cam_distance_change)); //Translate along the z axis away from camera glRotatef((GLfloat)camera->twist + (GLfloat)twist_change, (GLfloat)0.0, (GLfloat)0.0, (GLfloat)1.0); //Rotate around z axis (usually by 0) glRotatef((GLfloat)camera->elevation + (GLfloat)elevation_change, (GLfloat)1.0, (GLfloat)0.0, (GLfloat)0.0); //Rotate around x axis glRotatef((GLfloat)camera->azimuth + (GLfloat)azimuth_change, (GLfloat)0.0, (GLfloat)1.0, (GLfloat)0.0); //Rotate around y axis //Draw grid grid(); //Wireframe switching //If shaded mode, draw the model with shading, else only draw the wireframe if (shaded_mode){ //Setup polygon offset for drawing wire on shaded glPolygonOffset(1.0, 1.0); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glColor3f(1.0, 1.0, 1.0); //Draw the obj model draw_models(); glDisable(GL_POLYGON_OFFSET_FILL); //If show wireframe, render the wireframe on top of shaded object if (show_wireframe){ glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glColor3f(0.0, 0.0, 0.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); } } else { //Wireframe only glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); glDisable(GL_CULL_FACE); glColor3f(1.0, 1.0, 1.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE); } glutSwapBuffers(); } /** Sets the projection **/ static void set_projection() { glViewport(0, 0, (GLsizei) width, (GLsizei) height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Perspective mode or ortho float aspect_ratio = (float)width / (float)height; if (camera->perspective_mode){ gluPerspective(camera->fov, GLfloat(aspect_ratio), camera->near_plane, camera->far_plane); } else { //Keep aspect ratio float left, right, bottom, top, temp_ortho_zoom; temp_ortho_zoom = camera->ortho_zoom + ortho_zoom_change; if (aspect_ratio < 1.0){ left = -temp_ortho_zoom; right = temp_ortho_zoom; bottom = -temp_ortho_zoom * ( 1.0f / aspect_ratio ); top = temp_ortho_zoom * ( 1.0f / aspect_ratio ); } else { left = -temp_ortho_zoom * aspect_ratio; right = temp_ortho_zoom * aspect_ratio; bottom = -temp_ortho_zoom; top = temp_ortho_zoom; } glOrtho(left, right, bottom, top, -camera->far_plane, camera->far_plane); } } /** Reshape function **/ static void reshape(int new_width, int new_height) { //Set Global Variables width = new_width; height = new_height; set_projection(); } /** Keyboard Input **/ static void keyboard_func(unsigned char key, int mx, int my) { switch (key) { //Camera Motion for Assignment case 'u': camera->point_of_interest->y -= 0.02f; glutPostRedisplay(); break; case 'd': camera->point_of_interest->y += 0.02f; glutPostRedisplay(); break; case 'l': camera->point_of_interest->x -= 0.02f; glutPostRedisplay(); break; case 'r': camera->point_of_interest->x += 0.02f; glutPostRedisplay(); break; case 'f': camera->distance -= 0.2f; glutPostRedisplay(); break; case 'b': camera->distance += 0.2f; glutPostRedisplay(); break; //Views case 'c': //Reset views //Destroy and reinitialize camera delete camera; camera = new PolarCamera(); set_projection(); break; case 'w': //Show Wireframe show_wireframe = show_wireframe == false ? true : false; break; case 's': //Shaded Model shaded_mode = shaded_mode == false ? true : false; break; case 'p': //Perspective camera->perspective_mode = true; set_projection(); break; case 'o': //Ortho camera->perspective_mode = false; set_projection(); break; case 'z': //Zoom forward if (camera->perspective_mode){ camera->fov -= 1.5f; } else { camera->ortho_zoom -= 0.1f; } set_projection(); break; case 'Z': //Zoom back if (camera->perspective_mode){ camera->fov += 1.5f; } else { camera->ortho_zoom += 0.1f; } set_projection(); break; //Alternative zoom case '+': //Zoom forward if (camera->perspective_mode){ camera->fov -= 1.5f; } else { camera->ortho_zoom -= 0.1f; } set_projection(); break; case '-': //Zoom back if (camera->perspective_mode){ camera->fov += 1.5f; } else { camera->ortho_zoom += 0.1f; } set_projection(); break; //Models case '1': model = 0; break; case '2': model = 1; break; case '3': model = 2; break; case '4': model = 3; break; case '5': model = 4; break; case '6': model = 5; break; case '7': model = 6; break; case '8': model = 7; break; //Exit case 27: exit(0); } glutPostRedisplay(); } /** Function Keys **/ static void functionKeys(int key, int mx, int my) { } /** Mouse Clicks **/ static void mouse_clicks(int button, int state, int mx, int my) { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) { left_mouse_down = true; //Set mouse down state to true mouse_down_x = mx; //Record screen position of mouse when user clicked left button mouse_down_y = my; //cout << "Left mouse button clicked at:" << mx << ", " << my << endl; } else { left_mouse_down = false; //Add changes to camera camera->azimuth += azimuth_change; camera->elevation += elevation_change; //Reset deltas azimuth_change = 0; elevation_change = 0; } break; case GLUT_RIGHT_BUTTON: //Move camera forward and back if (state == GLUT_DOWN) { right_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { right_mouse_down = false; //Reset distance deltas camera->distance += cam_distance_change; cam_distance_change = 0; //Ortho camera->ortho_zoom += ortho_zoom_change; ortho_zoom_change = 0; } break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_DOWN) { middle_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { middle_mouse_down = false; //Reset panning deltas camera->point_of_interest->x += pan_x_change; camera->point_of_interest->y += pan_y_change; pan_x_change = 0; pan_y_change = 0; } break; } } /** Mouse Movement **/ static void mouse_move(int mx, int my) { //Only bother processing if mouse button is pressed //Left Mouse Button - Orbit if (left_mouse_down){ azimuth_change = - (float(mouse_down_x) - float(mx)) / float(width) * 90; elevation_change = - (float(mouse_down_y) - float(my)) / float(height) * 90; } //Right Mouse Button - Dolly if (right_mouse_down){ if (camera->perspective_mode){ cam_distance_change = (float(mouse_down_x) - float(mx)) / float(width) * 10; } else { ortho_zoom_change = (float(mouse_down_x) - float(mx)) / float(width); set_projection(); } } //Middle Mouse Button - Panning if (middle_mouse_down){ pan_x_change = (float(mouse_down_x) - float(mx)) / float(width) * 5; pan_y_change = (float(mouse_down_y) - float(my)) / float(height) * 5; } //Force redisplay if (left_mouse_down || middle_mouse_down || right_mouse_down){ glutPostRedisplay(); } } /** Enable lighting & materials **/ static void lighting() { glShadeModel(GL_SMOOTH); //glShadeModel(GL_FLAT); //Setup Material GLfloat mat_ambient[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_diffuse[] = {(GLfloat)0.9, (GLfloat)0.9, (GLfloat)0.9, (GLfloat)1.0}; GLfloat mat_specular[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_shininess[] = {(GLfloat)50}; glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); //Setup Light(s) GLfloat light_position[] = {30.0, 30.0, 30.0, 0.0}; GLfloat white_light[] = {1.0, 1.0, 1.0, 1.0}; glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light); glLightfv(GL_LIGHT0, GL_SPECULAR, white_light); //Setup Ambient Light //GLfloat lmodel_ambient[] = {(GLfloat)0.2, (GLfloat)0.2, (GLfloat)0.2, (GLfloat)1.0}; //Turn on lighting glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); } //Load Texture static void load_texture(char* filename) { texture = new MyBitmap(filename); if (!texture->loaded){ cout << "Could not load texture." << endl; exit(0); } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &texName); //Allocate Texture Name glBindTexture(GL_TEXTURE_2D, texName); //Select current texture glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texture->width, texture->height, 0, GL_RGB, GL_UNSIGNED_BYTE, texture->data); glEnable( GL_TEXTURE_2D ); delete texture; } /** Clear out the screen **/ static void init() { //Load models + uhtiger = new OBJModel("models/uhtiger.obj"); uhtiger->loadTexture("textures/uhtiger.bmp"); uhtiger->translate->z = 5.0f; m1abrams = new OBJModel("models/m1abrams.obj"); m1abrams->loadTexture("textures/M1_ABRAM.bmp"); m1abrams->translate->z = -5.0f; m1abrams->translate->x = -15.0f; humveehardtop = new OBJModel("models/humveehardtop.obj"); humveehardtop->loadTexture("textures/humveehardtop.bmp"); humveehardtop->translate->z = -5.0f; humveehardtop->translate->x = 15.0f; //Scene Graph rootNode = new Node(); - Transform* translatetest1 = new Transform(ROTATE); + TransformNode* translatetest1 = new TransformNode(ROTATE); translatetest1->rotate->y = 45.0f; rootNode->addChild(translatetest1); translatetest1->addChild(uhtiger); translatetest1->addChild(humveehardtop); translatetest1->addChild(m1abrams); + + /* + rootNode = new Node(); + OBJModel* cube = new OBJModel("models/pipe.obj"); + rootNode->addChild(cube); + + */ glClearColor(0.0, 0.0, 0.0, 0.0); //Set up lighting lighting(); //Anti-Aliasing /* glEnable (GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glLineWidth (1); */ //Backface culling glEnable(GL_CULL_FACE); } /** Main function **/ int main(int argc, char** argv) { //Get current directory cout << "Firing up OBJViewer" << endl; cout << "===================" << endl << endl; cout << "Camera Motion " << endl; cout << "Orbit: Left click and drag mouse" << endl; cout << "Panning: Middle click and drag mouse" << endl; cout << "Dolly: Right click and drag mouse" << endl << endl; cout << "Viewport Controls " << endl; cout << "w: Toggle wireframe" << endl; cout << "s: Toggle shaded mode" << endl; cout << "p: Perspective mode" << endl; cout << "o: Orthographic mode" << endl; cout << "+ or z: Zoom in" << endl; cout << "- or Z(shift-z): Zoom out" << endl; cout << "c: Reset view" << endl << endl; cout << "Escape: Quit" << endl; glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 100); glutCreateWindow("OBJViewer Test - Leonard Teo"); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard_func); glutSpecialFunc(functionKeys); glutMouseFunc(mouse_clicks); glutMotionFunc(mouse_move); glutMainLoop(); //Cleanup /* delete lightcycle_chassis; delete lightcycle_canopy; delete lightcycle_axel_front_right; delete lightcycle_axel_front_left; delete lightcycle_wheel_front_right; delete lightcycle_wheel_front_left; delete lightcycle_wheel_rear_right; delete lightcycle_wheel_rear_left; */ delete camera; exit(0); } \ No newline at end of file diff --git a/Transform.cpp b/TransformNode.cpp similarity index 81% rename from Transform.cpp rename to TransformNode.cpp index 654f2ad..f45f5ce 100644 --- a/Transform.cpp +++ b/TransformNode.cpp @@ -1,50 +1,50 @@ /* - * Transform.cpp - * OBJViewer + * TransformNode.cpp + * Scene graph node for handling transformations * * Created by Leonard Teo on 10-10-10. * Copyright 2010 Leonard Teo. All rights reserved. * */ -#include "Transform.h" +#include "TransformNode.h" -Transform::Transform(TransformType transformType) +TransformNode::TransformNode(TransformType transformType) { this->type = TRANSFORM; this->transformType = transformType; } -Transform::~Transform() +TransformNode::~TransformNode() { } //Do all translations then render child nodes -void Transform::render() +void TransformNode::render() { //Remember where we are glPushMatrix(); switch (this->transformType) { case TRANSLATE: glTranslatef((GLfloat)this->translate->x, (GLfloat)this->translate->y, (GLfloat)this->translate->z); break; case ROTATE: glRotatef((GLfloat)this->rotate->x, (GLfloat)1.0f, (GLfloat)0.0f, (GLfloat)0.0f); glRotatef((GLfloat)this->rotate->y, (GLfloat)0.0f, (GLfloat)1.0f, (GLfloat)0.0f); glRotatef((GLfloat)this->rotate->z, (GLfloat)0.0f, (GLfloat)0.0f, (GLfloat)1.0f); break; case SCALE: glScalef((GLfloat)this->scale->x, (GLfloat)this->scale->y, (GLfloat)this->scale->z); break; } for (int i=0; i<this->children->size(); i++) { this->children->at(i)->render(); } glPopMatrix(); } \ No newline at end of file diff --git a/Transform.h b/TransformNode.h similarity index 62% rename from Transform.h rename to TransformNode.h index bbfe5ae..8de1dcc 100644 --- a/Transform.h +++ b/TransformNode.h @@ -1,40 +1,40 @@ /* - * Transform.h - * OBJViewer + * TransformNode + * + * Scene Graph node for handling transformations * - * Created by Leonard Teo on 10-10-10. * Copyright 2010 Leonard Teo. All rights reserved. * */ -#ifndef TRANSFORM_H -#define TRANSFORM_H +#ifndef TRANSFORMNODE_H +#define TRANSFORMNODE_H #include "Node.h" #ifdef __APPLE__ #include <OpenGL/gl.h> #include <GLUT/GLUT.h> #else #include <GL/glut.h> #endif enum TransformType { TRANSLATE, SCALE, ROTATE }; -class Transform : public Node +class TransformNode : public Node { public: //Data members TransformType transformType; //Methods - Transform(enum TransformType); - ~Transform(); + TransformNode(enum TransformType); + ~TransformNode(); void render(); }; #endif diff --git a/models/cube.obj b/models/cube.obj new file mode 100644 index 0000000..f24b149 --- /dev/null +++ b/models/cube.obj @@ -0,0 +1,70 @@ +# This file uses centimeters as units for non-parametric coordinates. + +mtllib cube.mtl +g default +v -2.894048 -2.894048 2.894048 +v 2.894048 -2.894048 2.894048 +v -2.894048 2.894048 2.894048 +v 2.894048 2.894048 2.894048 +v -2.894048 2.894048 -2.894048 +v 2.894048 2.894048 -2.894048 +v -2.894048 -2.894048 -2.894048 +v 2.894048 -2.894048 -2.894048 +vt 0.375000 0.000000 +vt 0.625000 0.000000 +vt 0.375000 0.250000 +vt 0.625000 0.250000 +vt 0.375000 0.500000 +vt 0.625000 0.500000 +vt 0.375000 0.750000 +vt 0.625000 0.750000 +vt 0.375000 1.000000 +vt 0.625000 1.000000 +vt 0.875000 0.000000 +vt 0.875000 0.250000 +vt 0.125000 0.000000 +vt 0.125000 0.250000 +vn 0.000000 0.000000 1.000000 +vn 0.000000 0.000000 1.000000 +vn 0.000000 0.000000 1.000000 +vn 0.000000 0.000000 1.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 0.000000 -1.000000 +vn 0.000000 0.000000 -1.000000 +vn 0.000000 0.000000 -1.000000 +vn 0.000000 0.000000 -1.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 1.000000 0.000000 0.000000 +vn 1.000000 0.000000 0.000000 +vn 1.000000 0.000000 0.000000 +vn 1.000000 0.000000 0.000000 +vn -1.000000 0.000000 0.000000 +vn -1.000000 0.000000 0.000000 +vn -1.000000 0.000000 0.000000 +vn -1.000000 0.000000 0.000000 +s 1 +g pCube1 +usemtl initialShadingGroup +f 1/1/1 2/2/2 3/3/3 +f 3/3/3 2/2/2 4/4/4 +s 2 +f 3/3/5 4/4/6 5/5/7 +f 5/5/7 4/4/6 6/6/8 +s 3 +f 5/5/9 6/6/10 7/7/11 +f 7/7/11 6/6/10 8/8/12 +s 4 +f 7/7/13 8/8/14 1/9/15 +f 1/9/15 8/8/14 2/10/16 +s 5 +f 2/2/17 8/11/18 4/4/19 +f 4/4/19 8/11/18 6/12/20 +s 6 +f 7/13/21 1/1/22 5/14/23 +f 5/14/23 1/1/22 3/3/24 diff --git a/models/pipe.obj b/models/pipe.obj new file mode 100644 index 0000000..386572a --- /dev/null +++ b/models/pipe.obj @@ -0,0 +1,515 @@ +# This file uses centimeters as units for non-parametric coordinates. + +mtllib pipe.mtl +g default +v 1.256053 0.243935 -0.000000 +v 1.194577 0.243935 -0.388142 +v 1.016168 0.243935 -0.738289 +v 0.738289 0.243935 -1.016168 +v 0.388142 0.243935 -1.194577 +v -0.000000 0.243935 -1.256053 +v -0.388142 0.243935 -1.194577 +v -0.738289 0.243935 -1.016168 +v -1.016168 0.243935 -0.738289 +v -1.194577 0.243935 -0.388142 +v -1.256053 0.243935 -0.000000 +v -1.194577 0.243935 0.388142 +v -1.016168 0.243935 0.738289 +v -0.738289 0.243935 1.016168 +v -0.388142 0.243935 1.194578 +v 0.000000 0.243935 1.256053 +v 0.388142 0.243935 1.194578 +v 0.738290 0.243935 1.016169 +v 1.016169 0.243935 0.738290 +v 1.194578 0.243935 0.388142 +v 1.256053 2.756040 0.000000 +v 1.194577 2.756040 -0.388142 +v 1.016168 2.756040 -0.738289 +v 0.738289 2.756040 -1.016168 +v 0.388142 2.756040 -1.194577 +v -0.000000 2.756040 -1.256053 +v -0.388142 2.756040 -1.194577 +v -0.738289 2.756040 -1.016168 +v -1.016168 2.756040 -0.738289 +v -1.194577 2.756040 -0.388142 +v -1.256053 2.756040 0.000000 +v -1.194577 2.756040 0.388142 +v -1.016168 2.756040 0.738289 +v -0.738289 2.756040 1.016168 +v -0.388142 2.756040 1.194578 +v 0.000000 2.756040 1.256053 +v 0.388142 2.756040 1.194578 +v 0.738290 2.756040 1.016169 +v 1.016169 2.756040 0.738290 +v 1.194578 2.756040 0.388142 +v 2.512105 2.756040 0.000000 +v 2.389154 2.756040 -0.776283 +v 2.032336 2.756040 -1.476579 +v 1.476578 2.756040 -2.032336 +v 0.776283 2.756040 -2.389154 +v -0.000000 2.756040 -2.512105 +v -0.776283 2.756040 -2.389154 +v -1.476579 2.756040 -2.032336 +v -2.032336 2.756040 -1.476579 +v -2.389155 2.756040 -0.776283 +v -2.512106 2.756040 0.000000 +v -2.389155 2.756040 0.776283 +v -2.032336 2.756040 1.476579 +v -1.476579 2.756040 2.032337 +v -0.776284 2.756040 2.389155 +v 0.000000 2.756040 2.512106 +v 0.776284 2.756040 2.389155 +v 1.476579 2.756040 2.032337 +v 2.032337 2.756040 1.476579 +v 2.389156 2.756040 0.776284 +v 2.512105 0.243935 -0.000000 +v 2.389154 0.243935 -0.776283 +v 2.032336 0.243935 -1.476579 +v 1.476578 0.243935 -2.032336 +v 0.776283 0.243935 -2.389154 +v -0.000000 0.243935 -2.512105 +v -0.776283 0.243935 -2.389154 +v -1.476579 0.243935 -2.032336 +v -2.032336 0.243935 -1.476579 +v -2.389155 0.243935 -0.776283 +v -2.512106 0.243935 -0.000000 +v -2.389155 0.243935 0.776283 +v -2.032336 0.243935 1.476579 +v -1.476579 0.243935 2.032337 +v -0.776284 0.243935 2.389155 +v 0.000000 0.243935 2.512106 +v 0.776284 0.243935 2.389155 +v 1.476579 0.243935 2.032337 +v 2.032337 0.243935 1.476579 +v 2.389156 0.243935 0.776284 +vt 0.000000 1.000000 +vt 0.050000 1.000000 +vt 0.100000 1.000000 +vt 0.150000 1.000000 +vt 0.200000 1.000000 +vt 0.250000 1.000000 +vt 0.300000 1.000000 +vt 0.350000 1.000000 +vt 0.400000 1.000000 +vt 0.450000 1.000000 +vt 0.500000 1.000000 +vt 0.550000 1.000000 +vt 0.600000 1.000000 +vt 0.650000 1.000000 +vt 0.700000 1.000000 +vt 0.750000 1.000000 +vt 0.800000 1.000000 +vt 0.850000 1.000000 +vt 0.900000 1.000000 +vt 0.950000 1.000000 +vt 1.000000 1.000000 +vt 0.000000 0.750000 +vt 0.050000 0.750000 +vt 0.100000 0.750000 +vt 0.150000 0.750000 +vt 0.200000 0.750000 +vt 0.250000 0.750000 +vt 0.300000 0.750000 +vt 0.350000 0.750000 +vt 0.400000 0.750000 +vt 0.450000 0.750000 +vt 0.500000 0.750000 +vt 0.550000 0.750000 +vt 0.600000 0.750000 +vt 0.650000 0.750000 +vt 0.700000 0.750000 +vt 0.750000 0.750000 +vt 0.800000 0.750000 +vt 0.850000 0.750000 +vt 0.900000 0.750000 +vt 0.950000 0.750000 +vt 1.000000 0.750000 +vt 0.000000 0.500000 +vt 0.050000 0.500000 +vt 0.100000 0.500000 +vt 0.150000 0.500000 +vt 0.200000 0.500000 +vt 0.250000 0.500000 +vt 0.300000 0.500000 +vt 0.350000 0.500000 +vt 0.400000 0.500000 +vt 0.450000 0.500000 +vt 0.500000 0.500000 +vt 0.550000 0.500000 +vt 0.600000 0.500000 +vt 0.650000 0.500000 +vt 0.700000 0.500000 +vt 0.750000 0.500000 +vt 0.800000 0.500000 +vt 0.850000 0.500000 +vt 0.900000 0.500000 +vt 0.950000 0.500000 +vt 1.000000 0.500000 +vt 0.000000 0.250000 +vt 0.050000 0.250000 +vt 0.100000 0.250000 +vt 0.150000 0.250000 +vt 0.200000 0.250000 +vt 0.250000 0.250000 +vt 0.300000 0.250000 +vt 0.350000 0.250000 +vt 0.400000 0.250000 +vt 0.450000 0.250000 +vt 0.500000 0.250000 +vt 0.550000 0.250000 +vt 0.600000 0.250000 +vt 0.650000 0.250000 +vt 0.700000 0.250000 +vt 0.750000 0.250000 +vt 0.800000 0.250000 +vt 0.850000 0.250000 +vt 0.900000 0.250000 +vt 0.950000 0.250000 +vt 1.000000 0.250000 +vt 0.000000 0.000000 +vt 0.050000 0.000000 +vt 0.100000 0.000000 +vt 0.150000 0.000000 +vt 0.200000 0.000000 +vt 0.250000 0.000000 +vt 0.300000 0.000000 +vt 0.350000 0.000000 +vt 0.400000 0.000000 +vt 0.450000 0.000000 +vt 0.500000 0.000000 +vt 0.550000 0.000000 +vt 0.600000 0.000000 +vt 0.650000 0.000000 +vt 0.700000 0.000000 +vt 0.750000 0.000000 +vt 0.800000 0.000000 +vt 0.850000 0.000000 +vt 0.900000 0.000000 +vt 0.950000 0.000000 +vt 1.000000 0.000000 +vn -0.933442 0.000000 0.358728 +vn -0.998609 0.000000 0.052722 +vn -0.966026 0.000000 0.258446 +vn -0.998609 0.000000 -0.052720 +vn -0.776903 0.000000 0.629620 +vn -0.838881 0.000000 0.544315 +vn -0.544315 0.000000 0.838881 +vn -0.629620 0.000000 0.776903 +vn -0.258446 0.000000 0.966026 +vn -0.358728 0.000000 0.933442 +vn 0.052721 0.000000 0.998609 +vn -0.052721 0.000000 0.998609 +vn 0.358728 0.000000 0.933442 +vn 0.258446 0.000000 0.966026 +vn 0.629620 0.000000 0.776903 +vn 0.544315 0.000000 0.838881 +vn 0.838881 0.000000 0.544315 +vn 0.776903 0.000000 0.629620 +vn 0.966026 -0.000000 0.258446 +vn 0.933442 0.000000 0.358728 +vn 0.998609 -0.000000 -0.052721 +vn 0.998609 -0.000000 0.052721 +vn 0.933442 0.000000 -0.358728 +vn 0.966026 0.000000 -0.258446 +vn 0.776903 0.000000 -0.629620 +vn 0.838881 0.000000 -0.544315 +vn 0.544316 0.000000 -0.838881 +vn 0.629621 0.000000 -0.776903 +vn 0.258446 0.000000 -0.966026 +vn 0.358729 0.000000 -0.933442 +vn -0.052721 0.000000 -0.998609 +vn 0.052721 0.000000 -0.998609 +vn -0.358728 0.000000 -0.933442 +vn -0.258446 0.000000 -0.966026 +vn -0.629620 0.000000 -0.776903 +vn -0.544315 0.000000 -0.838881 +vn -0.838881 0.000000 -0.544315 +vn -0.776903 0.000000 -0.629620 +vn -0.966026 0.000000 -0.258445 +vn -0.933442 0.000000 -0.358728 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 -0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 -0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 -0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 -0.000000 +vn 0.000000 1.000000 -0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 -0.000000 +vn 0.000000 1.000000 -0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 -0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 -0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 -0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 -0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 -0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 -0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.933442 0.000000 -0.358728 +vn 0.998609 -0.000000 -0.052722 +vn 0.966026 0.000000 -0.258446 +vn 0.998609 -0.000000 0.052720 +vn 0.776903 0.000000 -0.629620 +vn 0.838881 0.000000 -0.544315 +vn 0.544315 0.000000 -0.838881 +vn 0.629620 0.000000 -0.776903 +vn 0.258446 0.000000 -0.966026 +vn 0.358728 0.000000 -0.933442 +vn -0.052721 0.000000 -0.998609 +vn 0.052721 0.000000 -0.998609 +vn -0.358728 0.000000 -0.933442 +vn -0.258446 0.000000 -0.966026 +vn -0.629620 0.000000 -0.776903 +vn -0.544315 0.000000 -0.838881 +vn -0.838881 0.000000 -0.544316 +vn -0.776903 0.000000 -0.629620 +vn -0.966026 0.000000 -0.258446 +vn -0.933442 0.000000 -0.358728 +vn -0.998609 0.000000 0.052721 +vn -0.998609 0.000000 -0.052721 +vn -0.933442 0.000000 0.358728 +vn -0.966026 0.000000 0.258446 +vn -0.776903 0.000000 0.629620 +vn -0.838881 0.000000 0.544315 +vn -0.544316 0.000000 0.838881 +vn -0.629621 0.000000 0.776903 +vn -0.258446 0.000000 0.966026 +vn -0.358729 0.000000 0.933442 +vn 0.052721 0.000000 0.998609 +vn -0.052721 0.000000 0.998609 +vn 0.358728 0.000000 0.933442 +vn 0.258446 0.000000 0.966026 +vn 0.629620 0.000000 0.776903 +vn 0.544315 0.000000 0.838881 +vn 0.838881 0.000000 0.544315 +vn 0.776903 0.000000 0.629620 +vn 0.966026 -0.000000 0.258445 +vn 0.933442 0.000000 0.358728 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +s 1 +g pPipe1 +usemtl initialShadingGroup +f 2/2/1 1/1/2 22/23/3 +f 22/23/3 1/1/2 21/22/4 +f 3/3/5 2/2/1 23/24/6 +f 23/24/6 2/2/1 22/23/3 +f 4/4/7 3/3/5 24/25/8 +f 24/25/8 3/3/5 23/24/6 +f 5/5/9 4/4/7 25/26/10 +f 25/26/10 4/4/7 24/25/8 +f 6/6/11 5/5/9 26/27/12 +f 26/27/12 5/5/9 25/26/10 +f 7/7/13 6/6/11 27/28/14 +f 27/28/14 6/6/11 26/27/12 +f 8/8/15 7/7/13 28/29/16 +f 28/29/16 7/7/13 27/28/14 +f 9/9/17 8/8/15 29/30/18 +f 29/30/18 8/8/15 28/29/16 +f 10/10/19 9/9/17 30/31/20 +f 30/31/20 9/9/17 29/30/18 +f 11/11/21 10/10/19 31/32/22 +f 31/32/22 10/10/19 30/31/20 +f 12/12/23 11/11/21 32/33/24 +f 32/33/24 11/11/21 31/32/22 +f 13/13/25 12/12/23 33/34/26 +f 33/34/26 12/12/23 32/33/24 +f 14/14/27 13/13/25 34/35/28 +f 34/35/28 13/13/25 33/34/26 +f 15/15/29 14/14/27 35/36/30 +f 35/36/30 14/14/27 34/35/28 +f 16/16/31 15/15/29 36/37/32 +f 36/37/32 15/15/29 35/36/30 +f 17/17/33 16/16/31 37/38/34 +f 37/38/34 16/16/31 36/37/32 +f 18/18/35 17/17/33 38/39/36 +f 38/39/36 17/17/33 37/38/34 +f 19/19/37 18/18/35 39/40/38 +f 39/40/38 18/18/35 38/39/36 +f 20/20/39 19/19/37 40/41/40 +f 40/41/40 19/19/37 39/40/38 +f 1/21/2 20/20/39 21/42/4 +f 21/42/4 20/20/39 40/41/40 +s 2 +f 22/23/41 21/22/42 42/44/43 +f 42/44/43 21/22/42 41/43/44 +f 23/24/45 22/23/41 43/45/46 +f 43/45/46 22/23/41 42/44/43 +f 24/25/47 23/24/45 44/46/48 +f 44/46/48 23/24/45 43/45/46 +f 25/26/49 24/25/47 45/47/50 +f 45/47/50 24/25/47 44/46/48 +f 26/27/51 25/26/49 46/48/52 +f 46/48/52 25/26/49 45/47/50 +f 27/28/53 26/27/51 47/49/54 +f 47/49/54 26/27/51 46/48/52 +f 28/29/55 27/28/53 48/50/56 +f 48/50/56 27/28/53 47/49/54 +f 29/30/57 28/29/55 49/51/58 +f 49/51/58 28/29/55 48/50/56 +f 30/31/59 29/30/57 50/52/60 +f 50/52/60 29/30/57 49/51/58 +f 31/32/61 30/31/59 51/53/62 +f 51/53/62 30/31/59 50/52/60 +f 32/33/63 31/32/61 52/54/64 +f 52/54/64 31/32/61 51/53/62 +f 33/34/65 32/33/63 53/55/66 +f 53/55/66 32/33/63 52/54/64 +f 34/35/67 33/34/65 54/56/68 +f 54/56/68 33/34/65 53/55/66 +f 35/36/69 34/35/67 55/57/70 +f 55/57/70 34/35/67 54/56/68 +f 36/37/71 35/36/69 56/58/72 +f 56/58/72 35/36/69 55/57/70 +f 37/38/73 36/37/71 57/59/74 +f 57/59/74 36/37/71 56/58/72 +f 38/39/75 37/38/73 58/60/76 +f 58/60/76 37/38/73 57/59/74 +f 39/40/77 38/39/75 59/61/78 +f 59/61/78 38/39/75 58/60/76 +f 40/41/79 39/40/77 60/62/80 +f 60/62/80 39/40/77 59/61/78 +f 21/42/42 40/41/79 41/63/44 +f 41/63/44 40/41/79 60/62/80 +s 3 +f 42/44/81 41/43/82 62/65/83 +f 62/65/83 41/43/82 61/64/84 +f 43/45/85 42/44/81 63/66/86 +f 63/66/86 42/44/81 62/65/83 +f 44/46/87 43/45/85 64/67/88 +f 64/67/88 43/45/85 63/66/86 +f 45/47/89 44/46/87 65/68/90 +f 65/68/90 44/46/87 64/67/88 +f 46/48/91 45/47/89 66/69/92 +f 66/69/92 45/47/89 65/68/90 +f 47/49/93 46/48/91 67/70/94 +f 67/70/94 46/48/91 66/69/92 +f 48/50/95 47/49/93 68/71/96 +f 68/71/96 47/49/93 67/70/94 +f 49/51/97 48/50/95 69/72/98 +f 69/72/98 48/50/95 68/71/96 +f 50/52/99 49/51/97 70/73/100 +f 70/73/100 49/51/97 69/72/98 +f 51/53/101 50/52/99 71/74/102 +f 71/74/102 50/52/99 70/73/100 +f 52/54/103 51/53/101 72/75/104 +f 72/75/104 51/53/101 71/74/102 +f 53/55/105 52/54/103 73/76/106 +f 73/76/106 52/54/103 72/75/104 +f 54/56/107 53/55/105 74/77/108 +f 74/77/108 53/55/105 73/76/106 +f 55/57/109 54/56/107 75/78/110 +f 75/78/110 54/56/107 74/77/108 +f 56/58/111 55/57/109 76/79/112 +f 76/79/112 55/57/109 75/78/110 +f 57/59/113 56/58/111 77/80/114 +f 77/80/114 56/58/111 76/79/112 +f 58/60/115 57/59/113 78/81/116 +f 78/81/116 57/59/113 77/80/114 +f 59/61/117 58/60/115 79/82/118 +f 79/82/118 58/60/115 78/81/116 +f 60/62/119 59/61/117 80/83/120 +f 80/83/120 59/61/117 79/82/118 +f 41/63/82 60/62/119 61/84/84 +f 61/84/84 60/62/119 80/83/120 +s 4 +f 62/65/121 61/64/122 2/86/123 +f 2/86/123 61/64/122 1/85/124 +f 63/66/125 62/65/121 3/87/126 +f 3/87/126 62/65/121 2/86/123 +f 64/67/127 63/66/125 4/88/128 +f 4/88/128 63/66/125 3/87/126 +f 65/68/129 64/67/127 5/89/130 +f 5/89/130 64/67/127 4/88/128 +f 66/69/131 65/68/129 6/90/132 +f 6/90/132 65/68/129 5/89/130 +f 67/70/133 66/69/131 7/91/134 +f 7/91/134 66/69/131 6/90/132 +f 68/71/135 67/70/133 8/92/136 +f 8/92/136 67/70/133 7/91/134 +f 69/72/137 68/71/135 9/93/138 +f 9/93/138 68/71/135 8/92/136 +f 70/73/139 69/72/137 10/94/140 +f 10/94/140 69/72/137 9/93/138 +f 71/74/141 70/73/139 11/95/142 +f 11/95/142 70/73/139 10/94/140 +f 72/75/143 71/74/141 12/96/144 +f 12/96/144 71/74/141 11/95/142 +f 73/76/145 72/75/143 13/97/146 +f 13/97/146 72/75/143 12/96/144 +f 74/77/147 73/76/145 14/98/148 +f 14/98/148 73/76/145 13/97/146 +f 75/78/149 74/77/147 15/99/150 +f 15/99/150 74/77/147 14/98/148 +f 76/79/151 75/78/149 16/100/152 +f 16/100/152 75/78/149 15/99/150 +f 77/80/153 76/79/151 17/101/154 +f 17/101/154 76/79/151 16/100/152 +f 78/81/155 77/80/153 18/102/156 +f 18/102/156 77/80/153 17/101/154 +f 79/82/157 78/81/155 19/103/158 +f 19/103/158 78/81/155 18/102/156 +f 80/83/159 79/82/157 20/104/160 +f 20/104/160 79/82/157 19/103/158 +f 61/84/122 80/83/159 1/105/124 +f 1/105/124 80/83/159 20/104/160 diff --git a/models/pyramid.obj b/models/pyramid.obj new file mode 100644 index 0000000..a87c384 --- /dev/null +++ b/models/pyramid.obj @@ -0,0 +1,45 @@ +# This file uses centimeters as units for non-parametric coordinates. + +mtllib pyramid.mtl +g default +v 0.000000 0.650858 -3.157871 +v -3.157871 0.650858 -0.000000 +v -0.000000 0.650858 3.157871 +v 3.157871 0.650858 0.000000 +v 0.000000 3.808729 0.000000 +vt 0.500000 0.000000 +vt 0.250000 0.250000 +vt 0.500000 0.500000 +vt 0.750000 0.250000 +vt 0.250000 0.500000 +vt 0.375000 0.500000 +vt 0.500000 0.500000 +vt 0.625000 0.500000 +vt 0.750000 0.500000 +vt 0.500000 1.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 -0.000000 +vn 0.000000 -1.000000 -0.000000 +vn -0.577350 0.577350 -0.577350 +vn -0.577350 0.577350 -0.577350 +vn -0.577350 0.577350 -0.577350 +vn -0.577350 0.577350 0.577350 +vn -0.577350 0.577350 0.577350 +vn -0.577350 0.577350 0.577350 +vn 0.577350 0.577350 0.577350 +vn 0.577350 0.577350 0.577350 +vn 0.577350 0.577350 0.577350 +vn 0.577350 0.577350 -0.577350 +vn 0.577350 0.577350 -0.577350 +vn 0.577350 0.577350 -0.577350 +s 1 +g pPyramid1 +usemtl initialShadingGroup +f 1/1/1 4/4/2 2/2/3 +f 2/2/3 4/4/2 3/3/4 +s off +f 1/5/5 2/6/6 5/10/7 +f 2/6/8 3/7/9 5/10/10 +f 3/7/11 4/8/12 5/10/13 +f 4/8/14 1/9/15 5/10/16
leonardteo/OBJViewer
0e74dd398f52f64a93ec1c99c5c696a6c05d0fe3
Added Transform node to Scene Graph
diff --git a/Camera.cpp b/Camera.cpp index 494df51..2d2bc86 100644 --- a/Camera.cpp +++ b/Camera.cpp @@ -1,18 +1,20 @@ /* * Camera.cpp * OBJViewer * * Created by Leonard Teo on 10-10-06. * Copyright 2010 Leonard Teo. All rights reserved. * */ #include "Camera.h" Camera::Camera() { + //Set node type + this->type = CAMERA; } Camera::~Camera() { } \ No newline at end of file diff --git a/Camera.h b/Camera.h index 0db381f..e6ea30f 100644 --- a/Camera.h +++ b/Camera.h @@ -1,32 +1,42 @@ /* * Camera.h * OBJViewer * * Created by Leonard Teo on 10-10-06. * Copyright 2010 Leonard Teo. All rights reserved. * */ +#ifndef CAMERA_H +#define CAMERA_H + #include "Node.h" enum CameraProjection { PERSPECTIVE, ORTHO }; enum CameraType { POLAR, FIRSTPERSON }; -class Camera: public Node + +/** + * Camera class extends Node + */ + +class Camera : public Node { public: //Data Members CameraProjection cameraProjection; CameraType cameraType; //Constructor/Destructor Camera(); ~Camera(); -}; \ No newline at end of file +}; + +#endif diff --git a/Node.cpp b/Node.cpp index 04d2bbc..1ffa071 100644 --- a/Node.cpp +++ b/Node.cpp @@ -1,39 +1,56 @@ /* * Node.cpp * OBJViewer * * Created by Leonard Teo on 10-10-05. * */ #include "Node.h" //Constructor Node::Node() { this->children = new vector<Node*>; this->scale = new Vector3(); this->rotate = new Vector3(); this->translate = new Vector3(); + this->id = ""; //Blank ID? } //Destructor Node::~Node() { this->children->clear(); delete this->children; delete this->scale; delete this->rotate; delete this->translate; delete this; } //Add a child void Node::addChild(Node* child) { + //Set the child node's parent as this one + child->setParent(this); + + //Add the child node this->children->push_back(child); + } -void Node::render() +//Set the parent +void Node::setParent(Node* parent) { -}; \ No newline at end of file + this->parent = parent; +} + +//Abstract method for rendering - must be overloaded by child classes +void Node::render() +{ + for (int i=0; i<this->children->size(); i++) + { + this->children->at(i)->render(); + } +} \ No newline at end of file diff --git a/Node.h b/Node.h index a2bba10..adef8a2 100644 --- a/Node.h +++ b/Node.h @@ -1,43 +1,47 @@ /* * Node.h * OBJViewer * * Created by Leonard Teo on 10-10-05. * */ #ifndef NODE_H #define NODE_H #include <vector> #include "Vector3.h" +#include <string> using namespace std; enum NodeType { POLYMESH, CAMERA, LIGHT, TRANSFORM }; class Node { public: //Data Members NodeType type; //The type of node this is - vector<Node*>* children; //Child nodes - + vector<Node*>* children; //Child nodes + Node* parent; //The node's parent + string id; //The node's ID so that we can search for a node + //Local Transforms Vector3* scale; //Local scaling Vector3* rotate; //Local rotation on x, y, z axes Vector3* translate; //Local translation //Methods Node(); ~Node(); void addChild(Node*); + void setParent(Node*); virtual void render(); private: }; #endif diff --git a/OBJModel.cpp b/OBJModel.cpp index f073a2b..48a4a3e 100644 --- a/OBJModel.cpp +++ b/OBJModel.cpp @@ -1,347 +1,346 @@ #include "OBJModel.h" using namespace std; //Constructor OBJModel::OBJModel(const char* fileName) { this->init(); this->load(fileName); } //Free memory OBJModel::~OBJModel(void) { //Free all vertices and normals for (int i=0; i<this->numVertices; i++) { delete this->vertices[i]; } delete this->vertices; for (int i=0; i<this->numNormals; i++) { delete this->normals[i]; } delete this->normals; for (int i=0; i<this->numUVs; i++) { delete this->uvs[i]; } delete this->uvs; delete this->index; delete this->normalsIndex; delete this->uvIndex; } //General class initialization void OBJModel::init() { this->numVertices = 0; this->numFaces = 0; this->numUVs = 0; this->numNormals = 0; this->vertices = NULL; this->uvs = NULL; this->index = NULL; this->normals = NULL; this->uvIndex = NULL; this->type = POLYMESH; this->hasTexture = false; } void OBJModel::load(const char* fileName) { char buffer[255]; //Open file for reading ifstream file; file.open(fileName); if (!file.is_open()) { //If file isn't open cout << "Error loading file: " << fileName << endl; return; } else { //First pass of reading the file counts the data while ( !file.eof() ){ //Read the line file.getline(buffer, 255); //Read the line switch(buffer[0]) { //Vertex case 'v': switch(buffer[1]) { case ' ': this->numVertices++; break; case 'n': this->numNormals++; break; case 't': this->numUVs++; break; } break; //Face case 'f': this->numFaces++; break; default: break; } } //end of file //Echo the stats printf("fileName: %s \n", fileName); printf("Vertices: %d \n", this->numVertices); printf("Vertex Normals: %d \n", this->numNormals); printf("Faces: %d \n", this->numFaces); printf("\n"); //Allocate memory for data //Init vertices this->vertices = new Vector3*[this->numVertices]; this->index = new int*[this->numFaces]; //Triangles now //Init normals this->normals = new Vector3*[this->numNormals]; this->normalsIndex = new int*[this->numFaces]; //Triangles //Init UV's this->uvs = new UV*[this->numUVs]; this->uvIndex = new int*[this->numFaces]; //Initialize each of the indices for (int i=0; i<this->numFaces; i++){ this->index[i] = new int[3]; this->normalsIndex[i] = new int[3]; this->uvIndex[i] = new int[3]; for (int j=0; j<3; j++){ this->index[i][j] = 0; this->normalsIndex[i][j] = 0; this->uvIndex[i][j] = 0; } } //Second pass of file to load data file.clear(); //Clear eof status file.seekg(0, ios::beg); //Move cursor to beginning int currentVertex = 0; int currentIndex = 0; int currentNormal = 0; int currentUV = 0; int currentUVIndex = 0; int currentNormalIndex = 0; while (!file.eof()){ //Read line file.getline(buffer, 255); switch (buffer[0]){ //Vertex case 'v': switch(buffer[1]){ case ' ': //Create new vertex this->vertices[currentVertex] = new Vector3(); sscanf(buffer, "v %f %f %f", &this->vertices[currentVertex]->x, &this->vertices[currentVertex]->y, &this->vertices[currentVertex]->z); currentVertex++; break; case 'n': //Create new vertex normal this->normals[currentNormal] = new Vector3(); sscanf(buffer, "vn %f %f %f", &this->normals[currentNormal]->x, &this->normals[currentNormal]->y, &this->normals[currentNormal]->z); currentNormal++; break; case 't': //Create new UV this->uvs[currentUV] = new UV(); sscanf(buffer, "vt %f %f", &this->uvs[currentUV]->u, &this->uvs[currentUV]->v); currentUV++; break; } break; case 'f': //sscanf(buffer, "f %d/%*d/%d %d/%*d/%d %d/%*d/%d", &this->index[currentIndex][0], &this->normalsIndex[currentNormalIndex][0], &this->index[currentIndex][1], &this->normalsIndex[currentNormalIndex][1], &this->index[currentIndex][2], &this->normalsIndex[currentNormalIndex][2]); sscanf(buffer, "f %d/%d/%d %d/%d/%d %d/%d/%d", &this->index[currentIndex][0], &this->uvIndex[currentUVIndex][0], &this->normalsIndex[currentNormalIndex][0], &this->index[currentIndex][1], &this->uvIndex[currentUVIndex][1], &this->normalsIndex[currentNormalIndex][1], &this->index[currentIndex][2], &this->uvIndex[currentUVIndex][2], &this->normalsIndex[currentNormalIndex][2]); currentIndex++; currentNormalIndex++; currentUVIndex++; break; } } //end of file //Release file pointer file.close(); } //Debug - echo out all the vertices and faces /* printf("Vertices: \n"); for(int i=0; i< this->numVertices; i++) { printf(" %f %f %f \n", this->vertices[i]->x, this->vertices[i]->y, this->vertices[i]->z ); } printf("\n\nUV coordinates: \n"); for (int i=0; i< this->numUVs; i++) { printf(" %f %f \n", this->uvs[i]->u, this->uvs[i]->v); } printf("\n\nVertex Normals: \n"); for(int i=0; i< this->numNormals ; i++) { printf(" %f %f %f \n", this->normals[i]->x, this->normals[i]->y, this->normals[i]->z); } printf("\n\nIndex/UV/Normal: \n"); for(int i=0; i< this->numFaces; i++){ printf(" %d/%d/%d %d/%d/%d %d/%d/%d\n", this->index[i][0], this->uvIndex[i][0], this->normalsIndex[i][0], this->index[i][1], this->uvIndex[i][1], this->normalsIndex[i][1], this->index[i][2], this->uvIndex[i][2], this->normalsIndex[i][2]); } */ //decrement all indices to cater for OpenGL (OBJ indices start at 1) for(int i = 0; i < this->numFaces; i++) { for(int j=0; j<3; j++){ this->index[i][j]--; this->normalsIndex[i][j]--; this->uvIndex[i][j]--; } } } void OBJModel::render() { for (int i=0; i<this->children->size(); i++) { this->children->at(i)->render(); } //Draw this glPushMatrix(); glTranslatef((GLfloat)this->translate->x, (GLfloat)this->translate->y, (GLfloat)this->translate->z); this->draw(); glPopMatrix(); } - /** Drawing routine **/ void OBJModel::draw() { //Load texture if (this->hasTexture) { glBindTexture(GL_TEXTURE_2D, this->texture); } //For each face, draw a Triangle glBegin(GL_TRIANGLES); for (int face = 0; face < this->numFaces; face++) { //Draw the vertex at each of the vertex numbders glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][0]]->u, (GLfloat)this->uvs[this->uvIndex[face][0]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][0]]->x, (GLfloat)this->normals[this->normalsIndex[face][0]]->y, (GLfloat)this->normals[this->normalsIndex[face][0]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][0]]->x, (GLfloat)this->vertices[this->index[face][0]]->y, (GLfloat)this->vertices[this->index[face][0]]->z); glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][1]]->u, (GLfloat)this->uvs[this->uvIndex[face][1]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][1]]->x, (GLfloat)this->normals[this->normalsIndex[face][1]]->y, (GLfloat)this->normals[this->normalsIndex[face][1]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][1]]->x, (GLfloat)this->vertices[this->index[face][1]]->y, (GLfloat)this->vertices[this->index[face][1]]->z); glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][2]]->u, (GLfloat)this->uvs[this->uvIndex[face][2]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][2]]->x, (GLfloat)this->normals[this->normalsIndex[face][2]]->y, (GLfloat)this->normals[this->normalsIndex[face][2]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][2]]->x, (GLfloat)this->vertices[this->index[face][2]]->y, (GLfloat)this->vertices[this->index[face][2]]->z); /* Non-Optimized code for debugging //Get vertex numbers int v1, v2, v3; v1 = this->index[face][0]; v2 = this->index[face][1]; v3 = this->index[face][2]; //Get Normal numbers int n1, n2, n3; n1 = this->normalsIndex[face][0]; n2 = this->normalsIndex[face][1]; n3 = this->normalsIndex[face][2]; //Get UVs int uv1, uv2, uv3; uv1 = this->uvIndex[face][0]; uv2 = this->uvIndex[face][1]; uv3 = this->uvIndex[face][2]; //Draw the vertex at each of the vertex numbders glTexCoord2f((GLfloat)this->uvs[uv1]->u, (GLfloat)this->uvs[uv1]->v); glNormal3f((GLfloat)this->normals[n1]->x, (GLfloat)this->normals[n1]->y, (GLfloat)this->normals[n1]->z); glVertex3f((GLfloat)this->vertices[v1]->x, (GLfloat)this->vertices[v1]->y, (GLfloat)this->vertices[v1]->z); glTexCoord2f((GLfloat)this->uvs[uv2]->u, (GLfloat)this->uvs[uv2]->v); glNormal3f((GLfloat)this->normals[n2]->x, (GLfloat)this->normals[n2]->y, (GLfloat)this->normals[n2]->z); glVertex3f((GLfloat)this->vertices[v2]->x, (GLfloat)this->vertices[v2]->y, (GLfloat)this->vertices[v2]->z); glTexCoord2f((GLfloat)this->uvs[uv3]->u, (GLfloat)this->uvs[uv3]->v); glNormal3f((GLfloat)this->normals[n3]->x, (GLfloat)this->normals[n3]->y, (GLfloat)this->normals[n3]->z); glVertex3f((GLfloat)this->vertices[v3]->x, (GLfloat)this->vertices[v3]->y, (GLfloat)this->vertices[v3]->z); */ } glEnd(); glFlush(); } /*** Load Texture ***/ void OBJModel::loadTexture(const char* fileName) { this->image = new MyBitmap(fileName); if (!image->loaded){ cout << "Could not load texture." << endl; exit(0); } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &this->texture); //Allocate Texture Name glBindTexture(GL_TEXTURE_2D, this->texture); //Select current texture glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->image->width, this->image->height, 0, GL_RGB, GL_UNSIGNED_BYTE, this->image->data); this->hasTexture = true; glEnable(GL_TEXTURE_2D); delete image; } \ No newline at end of file diff --git a/OBJModel.h b/OBJModel.h index 5b83d57..6c9e549 100644 --- a/OBJModel.h +++ b/OBJModel.h @@ -1,95 +1,96 @@ /** My attempt at an OBJ parser Leonard Teo Done: Only supports triangles - remember to triangulate all models To DO: - Generate normals if a model doesn't have them - Handle groups and materials **/ #ifndef OBJMODEL_H #define OBJMODEL_H #include <iostream> #include <fstream> #include <stdio.h> #include <string> -#ifdef OSX +#ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/GLUT.h> #else #include <GL/glut.h> #endif #include "Vector3.h" #include "MyBitmap.h" #include "Node.h" #include <vector> using namespace std; struct UV { float u; float v; }; class OBJModel: public Node { public: //Constructor OBJModel(const char* fileName); //Destructor ~OBJModel(void); //Load Texture void loadTexture(const char* fileName); //Draw the polygons using OpenGL calls void draw(); + void drawArray(); //Scene graph rendering call void render(); //Generate normals - TO DO void generateNormals(); private: //Private data members //Total number of vertices int numVertices; int numFaces; int numUVs; int numNormals; bool hasTexture; //Data Vector3** vertices; Vector3** normals; UV** uvs; int** index; //2 dimensional arrays: Note these are pointers so that we can do this: this->normals_index[i][j] int** normalsIndex; int** uvIndex; - + //Texture map MyBitmap* image; GLuint texture; //Initialize the arrays and variables void init(); //Load a model file void load(const char* fileName); }; #endif \ No newline at end of file diff --git a/OBJViewer.cpp b/OBJViewer.cpp index 6bca3a8..b3b517e 100644 --- a/OBJViewer.cpp +++ b/OBJViewer.cpp @@ -1,709 +1,703 @@ /** OBJ Viewer **/ #include <iostream> #include <string> -#ifdef OSX +#ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/GLUT.h> #else #include <GL/glut.h> #endif #include "PolarCamera.h" #include "OBJModel.h" #include "MyBitmap.h" #include "Node.h" +#include "Transform.h" using namespace std; //Default Screen Size const int WIDTH = 640; const int HEIGHT = 480; /** Global Variables **/ //Temporary screen width and height int width = WIDTH; int height = HEIGHT; //Mouse position int mouse_x; int mouse_y; int mouse_down_x; //Mouse position when a user clicks int mouse_down_y; //Mouse clicks states bool left_mouse_down = false; bool middle_mouse_down = false; bool right_mouse_down = false; //Model type int model = 0; //Show Wireframe bool show_wireframe = false; bool shaded_mode = true; //Camera - Polar view PolarCamera* camera = new PolarCamera(); //Temporary variables to facilitate Polar camera float azimuth_change = 0; float twist_change = 0; float elevation_change = 0; float cam_distance_change = 0.0; //Panning temporary variables float pan_x_down = 0; //When the pan button is pushed, record this float pan_y_down = 0; float pan_z_down = 0; float pan_x_change = 0; float pan_y_change = 0; //Orthographic zooming temporary variable float ortho_zoom_change = 0; //OBJ Models //OBJModel* objmodel; //Any objmodel for testing OBJModel* m1abrams; OBJModel* humveehardtop; OBJModel* uhtiger; //Texture MyBitmap* texture; static GLuint texName; //Scene Graph Node* rootNode; /** Draw a 24x24 grid **/ static void grid(int scale = 1) { //Turn off lighting for grid glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); //Start drawing lines glBegin(GL_LINES); glColor3f(0.5, 0.5, 0.5); for (int x=-12; x<=12; x++){ if (x != 0){ glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(-12*scale)); glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(12*scale)); } } for (int z=-12; z<=12; z++){ if (z != 0){ glVertex3f((GLfloat)(-12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); glVertex3f((GLfloat)(12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); } } glEnd(); //Make sure the lines at the origin are nice and different glBegin(GL_LINES); glColor3f(0.75, 0.75, 0.75); glVertex3f(0, 0, (GLfloat)(-12*scale)); glVertex3f(0, 0, (GLfloat)(12*scale)); glVertex3f((GLfloat)(-12*scale), 0, 0); glVertex3f((GLfloat)(12*scale), 0, 0); glEnd(); glFlush(); //Turn lighting back on glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); } static void draw_models() { //Draw using scene graph rootNode->render(); //Draw all three models (let's be awesome) /* glPushMatrix(); glTranslatef(-15, 0, 0); m1abrams->draw(); glPopMatrix(); uhtiger->draw(); glPushMatrix(); glTranslatef(15,0,0); humveehardtop->draw(); glPopMatrix(); */ //Switch model /* switch (model) { case 0: m1abrams->draw(); break; case 1: humveehardtop->draw(); break; case 2: uhtiger->draw(); break; } */ } /** Display function **/ static void display() { //Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); /** Camera setup **/ //Translate & Rotate Polar Views glTranslatef(-(GLfloat)(camera->point_of_interest->x + pan_x_change), (GLfloat)(camera->point_of_interest->y + pan_y_change), -((GLfloat)camera->distance + (GLfloat)cam_distance_change)); //Translate along the z axis away from camera glRotatef((GLfloat)camera->twist + (GLfloat)twist_change, (GLfloat)0.0, (GLfloat)0.0, (GLfloat)1.0); //Rotate around z axis (usually by 0) glRotatef((GLfloat)camera->elevation + (GLfloat)elevation_change, (GLfloat)1.0, (GLfloat)0.0, (GLfloat)0.0); //Rotate around x axis glRotatef((GLfloat)camera->azimuth + (GLfloat)azimuth_change, (GLfloat)0.0, (GLfloat)1.0, (GLfloat)0.0); //Rotate around y axis //Draw grid grid(); //Wireframe switching //If shaded mode, draw the model with shading, else only draw the wireframe if (shaded_mode){ //Setup polygon offset for drawing wire on shaded glPolygonOffset(1.0, 1.0); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glColor3f(1.0, 1.0, 1.0); //Draw the obj model draw_models(); glDisable(GL_POLYGON_OFFSET_FILL); //If show wireframe, render the wireframe on top of shaded object if (show_wireframe){ glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glColor3f(0.0, 0.0, 0.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); } } else { //Wireframe only glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); glDisable(GL_CULL_FACE); glColor3f(1.0, 1.0, 1.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE); } glutSwapBuffers(); } /** Sets the projection **/ static void set_projection() { glViewport(0, 0, (GLsizei) width, (GLsizei) height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Perspective mode or ortho float aspect_ratio = (float)width / (float)height; if (camera->perspective_mode){ gluPerspective(camera->fov, GLfloat(aspect_ratio), camera->near_plane, camera->far_plane); } else { //Keep aspect ratio float left, right, bottom, top, temp_ortho_zoom; temp_ortho_zoom = camera->ortho_zoom + ortho_zoom_change; if (aspect_ratio < 1.0){ left = -temp_ortho_zoom; right = temp_ortho_zoom; bottom = -temp_ortho_zoom * ( 1.0f / aspect_ratio ); top = temp_ortho_zoom * ( 1.0f / aspect_ratio ); } else { left = -temp_ortho_zoom * aspect_ratio; right = temp_ortho_zoom * aspect_ratio; bottom = -temp_ortho_zoom; top = temp_ortho_zoom; } glOrtho(left, right, bottom, top, -camera->far_plane, camera->far_plane); } } /** Reshape function **/ static void reshape(int new_width, int new_height) { //Set Global Variables width = new_width; height = new_height; set_projection(); } /** Keyboard Input **/ static void keyboard_func(unsigned char key, int mx, int my) { switch (key) { //Camera Motion for Assignment case 'u': camera->point_of_interest->y -= 0.02f; glutPostRedisplay(); break; case 'd': camera->point_of_interest->y += 0.02f; glutPostRedisplay(); break; case 'l': camera->point_of_interest->x -= 0.02f; glutPostRedisplay(); break; case 'r': camera->point_of_interest->x += 0.02f; glutPostRedisplay(); break; case 'f': camera->distance -= 0.2f; glutPostRedisplay(); break; case 'b': camera->distance += 0.2f; glutPostRedisplay(); break; //Views case 'c': //Reset views //Destroy and reinitialize camera delete camera; camera = new PolarCamera(); set_projection(); break; case 'w': //Show Wireframe show_wireframe = show_wireframe == false ? true : false; break; case 's': //Shaded Model shaded_mode = shaded_mode == false ? true : false; break; case 'p': //Perspective camera->perspective_mode = true; set_projection(); break; case 'o': //Ortho camera->perspective_mode = false; set_projection(); break; case 'z': //Zoom forward if (camera->perspective_mode){ camera->fov -= 1.5f; } else { camera->ortho_zoom -= 0.1f; } set_projection(); break; case 'Z': //Zoom back if (camera->perspective_mode){ camera->fov += 1.5f; } else { camera->ortho_zoom += 0.1f; } set_projection(); break; //Alternative zoom case '+': //Zoom forward if (camera->perspective_mode){ camera->fov -= 1.5f; } else { camera->ortho_zoom -= 0.1f; } set_projection(); break; case '-': //Zoom back if (camera->perspective_mode){ camera->fov += 1.5f; } else { camera->ortho_zoom += 0.1f; } set_projection(); break; //Models case '1': model = 0; break; case '2': model = 1; break; case '3': model = 2; break; case '4': model = 3; break; case '5': model = 4; break; case '6': model = 5; break; case '7': model = 6; break; case '8': model = 7; break; //Exit case 27: exit(0); } glutPostRedisplay(); } /** Function Keys **/ static void functionKeys(int key, int mx, int my) { } /** Mouse Clicks **/ static void mouse_clicks(int button, int state, int mx, int my) { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) { left_mouse_down = true; //Set mouse down state to true mouse_down_x = mx; //Record screen position of mouse when user clicked left button mouse_down_y = my; //cout << "Left mouse button clicked at:" << mx << ", " << my << endl; } else { left_mouse_down = false; //Add changes to camera camera->azimuth += azimuth_change; camera->elevation += elevation_change; //Reset deltas azimuth_change = 0; elevation_change = 0; } break; case GLUT_RIGHT_BUTTON: //Move camera forward and back if (state == GLUT_DOWN) { right_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { right_mouse_down = false; //Reset distance deltas camera->distance += cam_distance_change; cam_distance_change = 0; //Ortho camera->ortho_zoom += ortho_zoom_change; ortho_zoom_change = 0; } break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_DOWN) { middle_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { middle_mouse_down = false; //Reset panning deltas camera->point_of_interest->x += pan_x_change; camera->point_of_interest->y += pan_y_change; pan_x_change = 0; pan_y_change = 0; } break; } } /** Mouse Movement **/ static void mouse_move(int mx, int my) { //Only bother processing if mouse button is pressed //Left Mouse Button - Orbit if (left_mouse_down){ azimuth_change = - (float(mouse_down_x) - float(mx)) / float(width) * 90; elevation_change = - (float(mouse_down_y) - float(my)) / float(height) * 90; } //Right Mouse Button - Dolly if (right_mouse_down){ if (camera->perspective_mode){ cam_distance_change = (float(mouse_down_x) - float(mx)) / float(width) * 10; } else { ortho_zoom_change = (float(mouse_down_x) - float(mx)) / float(width); set_projection(); } } //Middle Mouse Button - Panning if (middle_mouse_down){ pan_x_change = (float(mouse_down_x) - float(mx)) / float(width) * 5; pan_y_change = (float(mouse_down_y) - float(my)) / float(height) * 5; } //Force redisplay if (left_mouse_down || middle_mouse_down || right_mouse_down){ glutPostRedisplay(); } } /** Enable lighting & materials **/ static void lighting() { glShadeModel(GL_SMOOTH); //glShadeModel(GL_FLAT); //Setup Material GLfloat mat_ambient[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_diffuse[] = {(GLfloat)0.9, (GLfloat)0.9, (GLfloat)0.9, (GLfloat)1.0}; GLfloat mat_specular[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_shininess[] = {(GLfloat)50}; glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); //Setup Light(s) GLfloat light_position[] = {30.0, 30.0, 30.0, 0.0}; GLfloat white_light[] = {1.0, 1.0, 1.0, 1.0}; glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light); glLightfv(GL_LIGHT0, GL_SPECULAR, white_light); //Setup Ambient Light //GLfloat lmodel_ambient[] = {(GLfloat)0.2, (GLfloat)0.2, (GLfloat)0.2, (GLfloat)1.0}; //Turn on lighting glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); } //Load Texture static void load_texture(char* filename) { texture = new MyBitmap(filename); if (!texture->loaded){ cout << "Could not load texture." << endl; exit(0); } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &texName); //Allocate Texture Name glBindTexture(GL_TEXTURE_2D, texName); //Select current texture glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texture->width, texture->height, 0, GL_RGB, GL_UNSIGNED_BYTE, texture->data); glEnable( GL_TEXTURE_2D ); delete texture; } /** Clear out the screen **/ static void init() { //Load models uhtiger = new OBJModel("models/uhtiger.obj"); uhtiger->loadTexture("textures/uhtiger.bmp"); uhtiger->translate->z = 5.0f; m1abrams = new OBJModel("models/m1abrams.obj"); m1abrams->loadTexture("textures/M1_ABRAM.bmp"); m1abrams->translate->z = -5.0f; m1abrams->translate->x = -15.0f; humveehardtop = new OBJModel("models/humveehardtop.obj"); humveehardtop->loadTexture("textures/humveehardtop.bmp"); humveehardtop->translate->z = -5.0f; humveehardtop->translate->x = 15.0f; //Scene Graph - rootNode = uhtiger; - rootNode->addChild(humveehardtop); - rootNode->addChild(m1abrams); - - //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\quakeplasma.obj"); - //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\uhtiger.obj"); - //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\humveehardtop.obj"); - //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\ussoldier1.obj"); - - //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\M1_ABRAM.bmp"); - //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\plasma.bmp"); - //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\uhtiger.bmp"); - //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\humveehardtop.bmp"); - //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\ussoldier01.bmp"); + rootNode = new Node(); + Transform* translatetest1 = new Transform(ROTATE); + translatetest1->rotate->y = 45.0f; + rootNode->addChild(translatetest1); + translatetest1->addChild(uhtiger); + translatetest1->addChild(humveehardtop); + translatetest1->addChild(m1abrams); glClearColor(0.0, 0.0, 0.0, 0.0); //Set up lighting lighting(); //Anti-Aliasing /* glEnable (GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glLineWidth (1); */ //Backface culling glEnable(GL_CULL_FACE); } /** Main function **/ int main(int argc, char** argv) { //Get current directory cout << "Firing up OBJViewer" << endl; cout << "===================" << endl << endl; cout << "Camera Motion " << endl; cout << "Orbit: Left click and drag mouse" << endl; cout << "Panning: Middle click and drag mouse" << endl; cout << "Dolly: Right click and drag mouse" << endl << endl; cout << "Viewport Controls " << endl; cout << "w: Toggle wireframe" << endl; cout << "s: Toggle shaded mode" << endl; cout << "p: Perspective mode" << endl; cout << "o: Orthographic mode" << endl; cout << "+ or z: Zoom in" << endl; cout << "- or Z(shift-z): Zoom out" << endl; cout << "c: Reset view" << endl << endl; cout << "Escape: Quit" << endl; glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 100); glutCreateWindow("OBJViewer Test - Leonard Teo"); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard_func); glutSpecialFunc(functionKeys); glutMouseFunc(mouse_clicks); glutMotionFunc(mouse_move); glutMainLoop(); //Cleanup /* delete lightcycle_chassis; delete lightcycle_canopy; delete lightcycle_axel_front_right; delete lightcycle_axel_front_left; delete lightcycle_wheel_front_right; delete lightcycle_wheel_front_left; delete lightcycle_wheel_rear_right; delete lightcycle_wheel_rear_left; */ delete camera; exit(0); } \ No newline at end of file diff --git a/PolarCamera.h b/PolarCamera.h index c54d354..74d845c 100644 --- a/PolarCamera.h +++ b/PolarCamera.h @@ -1,36 +1,36 @@ /** Polar Camera Class @author Leonard Teo **/ #ifndef POLARCAMERA #define POLARCAMERA #include "Vector3.h" class PolarCamera { public: //Members Vector3* point_of_interest; //Where the camera should be looking at float twist; //Roll float elevation; //Pitch float azimuth; //Heading - float distance; //Distance from point of interest + float distance; //Distance from point of interest float fov; //Field of View float near_plane; //Near clipping plane float far_plane; //Far clipping plane bool perspective_mode; //Switch between perspective and ortho //Ortho float ortho_zoom; //The orthographic zoom factor //Methods PolarCamera(void); ~PolarCamera(void); }; #endif \ No newline at end of file diff --git a/Transform.cpp b/Transform.cpp new file mode 100644 index 0000000..654f2ad --- /dev/null +++ b/Transform.cpp @@ -0,0 +1,50 @@ +/* + * Transform.cpp + * OBJViewer + * + * Created by Leonard Teo on 10-10-10. + * Copyright 2010 Leonard Teo. All rights reserved. + * + */ + +#include "Transform.h" + +Transform::Transform(TransformType transformType) +{ + this->type = TRANSFORM; + this->transformType = transformType; +} + +Transform::~Transform() +{ +} + +//Do all translations then render child nodes +void Transform::render() +{ + //Remember where we are + glPushMatrix(); + + switch (this->transformType) + { + case TRANSLATE: + glTranslatef((GLfloat)this->translate->x, (GLfloat)this->translate->y, (GLfloat)this->translate->z); + break; + case ROTATE: + glRotatef((GLfloat)this->rotate->x, (GLfloat)1.0f, (GLfloat)0.0f, (GLfloat)0.0f); + glRotatef((GLfloat)this->rotate->y, (GLfloat)0.0f, (GLfloat)1.0f, (GLfloat)0.0f); + glRotatef((GLfloat)this->rotate->z, (GLfloat)0.0f, (GLfloat)0.0f, (GLfloat)1.0f); + break; + case SCALE: + glScalef((GLfloat)this->scale->x, (GLfloat)this->scale->y, (GLfloat)this->scale->z); + break; + } + + for (int i=0; i<this->children->size(); i++) + { + this->children->at(i)->render(); + } + + glPopMatrix(); + +} \ No newline at end of file diff --git a/Transform.h b/Transform.h new file mode 100644 index 0000000..bbfe5ae --- /dev/null +++ b/Transform.h @@ -0,0 +1,40 @@ +/* + * Transform.h + * OBJViewer + * + * Created by Leonard Teo on 10-10-10. + * Copyright 2010 Leonard Teo. All rights reserved. + * + */ + +#ifndef TRANSFORM_H +#define TRANSFORM_H + +#include "Node.h" + +#ifdef __APPLE__ + #include <OpenGL/gl.h> + #include <GLUT/GLUT.h> +#else + #include <GL/glut.h> +#endif + +enum TransformType { + TRANSLATE, SCALE, ROTATE +}; + +class Transform : public Node +{ + +public: + //Data members + TransformType transformType; + + //Methods + Transform(enum TransformType); + ~Transform(); + void render(); + +}; + +#endif
leonardteo/OBJViewer
0137eaaeecf53588cc3bab94a0876d10635c4b2d
Added Camera class:
diff --git a/Camera.cpp b/Camera.cpp new file mode 100644 index 0000000..494df51 --- /dev/null +++ b/Camera.cpp @@ -0,0 +1,18 @@ +/* + * Camera.cpp + * OBJViewer + * + * Created by Leonard Teo on 10-10-06. + * Copyright 2010 Leonard Teo. All rights reserved. + * + */ + +#include "Camera.h" + +Camera::Camera() +{ +} + +Camera::~Camera() +{ +} \ No newline at end of file diff --git a/Camera.h b/Camera.h new file mode 100644 index 0000000..0db381f --- /dev/null +++ b/Camera.h @@ -0,0 +1,32 @@ +/* + * Camera.h + * OBJViewer + * + * Created by Leonard Teo on 10-10-06. + * Copyright 2010 Leonard Teo. All rights reserved. + * + */ + +#include "Node.h" + +enum CameraProjection { + PERSPECTIVE, ORTHO +}; + +enum CameraType { + POLAR, FIRSTPERSON +}; + +class Camera: public Node +{ +public: + + //Data Members + CameraProjection cameraProjection; + CameraType cameraType; + + //Constructor/Destructor + Camera(); + ~Camera(); + +}; \ No newline at end of file diff --git a/Node.cpp b/Node.cpp index 5db8893..04d2bbc 100644 --- a/Node.cpp +++ b/Node.cpp @@ -1,37 +1,39 @@ /* * Node.cpp * OBJViewer * * Created by Leonard Teo on 10-10-05. * */ #include "Node.h" //Constructor Node::Node() { this->children = new vector<Node*>; this->scale = new Vector3(); this->rotate = new Vector3(); this->translate = new Vector3(); } //Destructor Node::~Node() { + this->children->clear(); delete this->children; delete this->scale; delete this->rotate; delete this->translate; + delete this; } //Add a child void Node::addChild(Node* child) { this->children->push_back(child); } void Node::render() { }; \ No newline at end of file diff --git a/OBJModel.cpp b/OBJModel.cpp index e7f450b..f073a2b 100644 --- a/OBJModel.cpp +++ b/OBJModel.cpp @@ -1,324 +1,347 @@ #include "OBJModel.h" using namespace std; //Constructor OBJModel::OBJModel(const char* fileName) { this->init(); this->load(fileName); } //Free memory OBJModel::~OBJModel(void) { + //Free all vertices and normals + for (int i=0; i<this->numVertices; i++) + { + delete this->vertices[i]; + } delete this->vertices; + + for (int i=0; i<this->numNormals; i++) + { + delete this->normals[i]; + } delete this->normals; + + for (int i=0; i<this->numUVs; i++) + { + delete this->uvs[i]; + } delete this->uvs; + delete this->index; delete this->normalsIndex; delete this->uvIndex; } //General class initialization void OBJModel::init() { this->numVertices = 0; this->numFaces = 0; this->numUVs = 0; this->numNormals = 0; this->vertices = NULL; this->uvs = NULL; this->index = NULL; this->normals = NULL; this->uvIndex = NULL; this->type = POLYMESH; + this->hasTexture = false; } void OBJModel::load(const char* fileName) { char buffer[255]; //Open file for reading ifstream file; file.open(fileName); if (!file.is_open()) { //If file isn't open cout << "Error loading file: " << fileName << endl; return; } else { //First pass of reading the file counts the data while ( !file.eof() ){ //Read the line file.getline(buffer, 255); //Read the line switch(buffer[0]) { //Vertex case 'v': switch(buffer[1]) { case ' ': this->numVertices++; break; case 'n': this->numNormals++; break; case 't': this->numUVs++; break; } break; //Face case 'f': this->numFaces++; break; default: break; } } //end of file //Echo the stats printf("fileName: %s \n", fileName); printf("Vertices: %d \n", this->numVertices); printf("Vertex Normals: %d \n", this->numNormals); printf("Faces: %d \n", this->numFaces); printf("\n"); //Allocate memory for data //Init vertices this->vertices = new Vector3*[this->numVertices]; this->index = new int*[this->numFaces]; //Triangles now //Init normals this->normals = new Vector3*[this->numNormals]; this->normalsIndex = new int*[this->numFaces]; //Triangles //Init UV's this->uvs = new UV*[this->numUVs]; this->uvIndex = new int*[this->numFaces]; //Initialize each of the indices for (int i=0; i<this->numFaces; i++){ this->index[i] = new int[3]; this->normalsIndex[i] = new int[3]; this->uvIndex[i] = new int[3]; for (int j=0; j<3; j++){ this->index[i][j] = 0; this->normalsIndex[i][j] = 0; this->uvIndex[i][j] = 0; } } //Second pass of file to load data file.clear(); //Clear eof status file.seekg(0, ios::beg); //Move cursor to beginning int currentVertex = 0; int currentIndex = 0; int currentNormal = 0; int currentUV = 0; int currentUVIndex = 0; int currentNormalIndex = 0; while (!file.eof()){ //Read line file.getline(buffer, 255); switch (buffer[0]){ //Vertex case 'v': switch(buffer[1]){ case ' ': //Create new vertex this->vertices[currentVertex] = new Vector3(); sscanf(buffer, "v %f %f %f", &this->vertices[currentVertex]->x, &this->vertices[currentVertex]->y, &this->vertices[currentVertex]->z); currentVertex++; break; case 'n': //Create new vertex normal this->normals[currentNormal] = new Vector3(); sscanf(buffer, "vn %f %f %f", &this->normals[currentNormal]->x, &this->normals[currentNormal]->y, &this->normals[currentNormal]->z); currentNormal++; break; case 't': //Create new UV this->uvs[currentUV] = new UV(); sscanf(buffer, "vt %f %f", &this->uvs[currentUV]->u, &this->uvs[currentUV]->v); currentUV++; break; } break; case 'f': //sscanf(buffer, "f %d/%*d/%d %d/%*d/%d %d/%*d/%d", &this->index[currentIndex][0], &this->normalsIndex[currentNormalIndex][0], &this->index[currentIndex][1], &this->normalsIndex[currentNormalIndex][1], &this->index[currentIndex][2], &this->normalsIndex[currentNormalIndex][2]); sscanf(buffer, "f %d/%d/%d %d/%d/%d %d/%d/%d", &this->index[currentIndex][0], &this->uvIndex[currentUVIndex][0], &this->normalsIndex[currentNormalIndex][0], &this->index[currentIndex][1], &this->uvIndex[currentUVIndex][1], &this->normalsIndex[currentNormalIndex][1], &this->index[currentIndex][2], &this->uvIndex[currentUVIndex][2], &this->normalsIndex[currentNormalIndex][2]); currentIndex++; currentNormalIndex++; currentUVIndex++; break; } } //end of file //Release file pointer file.close(); } //Debug - echo out all the vertices and faces /* printf("Vertices: \n"); for(int i=0; i< this->numVertices; i++) { printf(" %f %f %f \n", this->vertices[i]->x, this->vertices[i]->y, this->vertices[i]->z ); } printf("\n\nUV coordinates: \n"); for (int i=0; i< this->numUVs; i++) { printf(" %f %f \n", this->uvs[i]->u, this->uvs[i]->v); } printf("\n\nVertex Normals: \n"); for(int i=0; i< this->numNormals ; i++) { printf(" %f %f %f \n", this->normals[i]->x, this->normals[i]->y, this->normals[i]->z); } printf("\n\nIndex/UV/Normal: \n"); for(int i=0; i< this->numFaces; i++){ printf(" %d/%d/%d %d/%d/%d %d/%d/%d\n", this->index[i][0], this->uvIndex[i][0], this->normalsIndex[i][0], this->index[i][1], this->uvIndex[i][1], this->normalsIndex[i][1], this->index[i][2], this->uvIndex[i][2], this->normalsIndex[i][2]); } */ //decrement all indices to cater for OpenGL (OBJ indices start at 1) for(int i = 0; i < this->numFaces; i++) { for(int j=0; j<3; j++){ this->index[i][j]--; this->normalsIndex[i][j]--; this->uvIndex[i][j]--; } } } void OBJModel::render() { for (int i=0; i<this->children->size(); i++) { this->children->at(i)->render(); } //Draw this glPushMatrix(); glTranslatef((GLfloat)this->translate->x, (GLfloat)this->translate->y, (GLfloat)this->translate->z); this->draw(); glPopMatrix(); } /** Drawing routine **/ void OBJModel::draw() { //Load texture - glBindTexture(GL_TEXTURE_2D, this->texture); - + if (this->hasTexture) + { + glBindTexture(GL_TEXTURE_2D, this->texture); + } + //For each face, draw a Triangle glBegin(GL_TRIANGLES); for (int face = 0; face < this->numFaces; face++) { //Draw the vertex at each of the vertex numbders glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][0]]->u, (GLfloat)this->uvs[this->uvIndex[face][0]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][0]]->x, (GLfloat)this->normals[this->normalsIndex[face][0]]->y, (GLfloat)this->normals[this->normalsIndex[face][0]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][0]]->x, (GLfloat)this->vertices[this->index[face][0]]->y, (GLfloat)this->vertices[this->index[face][0]]->z); glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][1]]->u, (GLfloat)this->uvs[this->uvIndex[face][1]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][1]]->x, (GLfloat)this->normals[this->normalsIndex[face][1]]->y, (GLfloat)this->normals[this->normalsIndex[face][1]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][1]]->x, (GLfloat)this->vertices[this->index[face][1]]->y, (GLfloat)this->vertices[this->index[face][1]]->z); glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][2]]->u, (GLfloat)this->uvs[this->uvIndex[face][2]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][2]]->x, (GLfloat)this->normals[this->normalsIndex[face][2]]->y, (GLfloat)this->normals[this->normalsIndex[face][2]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][2]]->x, (GLfloat)this->vertices[this->index[face][2]]->y, (GLfloat)this->vertices[this->index[face][2]]->z); /* Non-Optimized code for debugging //Get vertex numbers int v1, v2, v3; v1 = this->index[face][0]; v2 = this->index[face][1]; v3 = this->index[face][2]; //Get Normal numbers int n1, n2, n3; n1 = this->normalsIndex[face][0]; n2 = this->normalsIndex[face][1]; n3 = this->normalsIndex[face][2]; //Get UVs int uv1, uv2, uv3; uv1 = this->uvIndex[face][0]; uv2 = this->uvIndex[face][1]; uv3 = this->uvIndex[face][2]; //Draw the vertex at each of the vertex numbders glTexCoord2f((GLfloat)this->uvs[uv1]->u, (GLfloat)this->uvs[uv1]->v); glNormal3f((GLfloat)this->normals[n1]->x, (GLfloat)this->normals[n1]->y, (GLfloat)this->normals[n1]->z); glVertex3f((GLfloat)this->vertices[v1]->x, (GLfloat)this->vertices[v1]->y, (GLfloat)this->vertices[v1]->z); glTexCoord2f((GLfloat)this->uvs[uv2]->u, (GLfloat)this->uvs[uv2]->v); glNormal3f((GLfloat)this->normals[n2]->x, (GLfloat)this->normals[n2]->y, (GLfloat)this->normals[n2]->z); glVertex3f((GLfloat)this->vertices[v2]->x, (GLfloat)this->vertices[v2]->y, (GLfloat)this->vertices[v2]->z); glTexCoord2f((GLfloat)this->uvs[uv3]->u, (GLfloat)this->uvs[uv3]->v); glNormal3f((GLfloat)this->normals[n3]->x, (GLfloat)this->normals[n3]->y, (GLfloat)this->normals[n3]->z); glVertex3f((GLfloat)this->vertices[v3]->x, (GLfloat)this->vertices[v3]->y, (GLfloat)this->vertices[v3]->z); */ } glEnd(); glFlush(); } /*** Load Texture ***/ void OBJModel::loadTexture(const char* fileName) { this->image = new MyBitmap(fileName); if (!image->loaded){ cout << "Could not load texture." << endl; exit(0); } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &this->texture); //Allocate Texture Name glBindTexture(GL_TEXTURE_2D, this->texture); //Select current texture glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->image->width, this->image->height, 0, GL_RGB, GL_UNSIGNED_BYTE, this->image->data); - glEnable( GL_TEXTURE_2D ); + this->hasTexture = true; + + glEnable(GL_TEXTURE_2D); + delete image; } \ No newline at end of file diff --git a/OBJModel.h b/OBJModel.h index 549cac9..5b83d57 100644 --- a/OBJModel.h +++ b/OBJModel.h @@ -1,93 +1,95 @@ /** My attempt at an OBJ parser Leonard Teo Done: Only supports triangles - remember to triangulate all models To DO: - Generate normals if a model doesn't have them - Handle groups and materials **/ #ifndef OBJMODEL_H #define OBJMODEL_H #include <iostream> #include <fstream> #include <stdio.h> #include <string> #ifdef OSX #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/GLUT.h> #else #include <GL/glut.h> #endif #include "Vector3.h" #include "MyBitmap.h" #include "Node.h" #include <vector> using namespace std; struct UV { float u; float v; }; class OBJModel: public Node { public: //Constructor OBJModel(const char* fileName); //Destructor ~OBJModel(void); //Load Texture void loadTexture(const char* fileName); //Draw the polygons using OpenGL calls void draw(); //Scene graph rendering call void render(); //Generate normals - TO DO void generateNormals(); private: //Private data members //Total number of vertices int numVertices; int numFaces; int numUVs; int numNormals; + + bool hasTexture; //Data Vector3** vertices; Vector3** normals; UV** uvs; int** index; //2 dimensional arrays: Note these are pointers so that we can do this: this->normals_index[i][j] int** normalsIndex; int** uvIndex; //Texture map MyBitmap* image; GLuint texture; //Initialize the arrays and variables void init(); //Load a model file void load(const char* fileName); }; #endif \ No newline at end of file diff --git a/OBJViewer.cpp b/OBJViewer.cpp index 2af7fae..6bca3a8 100644 --- a/OBJViewer.cpp +++ b/OBJViewer.cpp @@ -124,589 +124,586 @@ static void grid(int scale = 1) //Turn lighting back on glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); } static void draw_models() { //Draw using scene graph rootNode->render(); //Draw all three models (let's be awesome) /* glPushMatrix(); glTranslatef(-15, 0, 0); m1abrams->draw(); glPopMatrix(); uhtiger->draw(); glPushMatrix(); glTranslatef(15,0,0); humveehardtop->draw(); glPopMatrix(); */ //Switch model /* switch (model) { case 0: m1abrams->draw(); break; case 1: humveehardtop->draw(); break; case 2: uhtiger->draw(); break; } */ } /** Display function **/ static void display() { //Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); /** Camera setup **/ //Translate & Rotate Polar Views glTranslatef(-(GLfloat)(camera->point_of_interest->x + pan_x_change), (GLfloat)(camera->point_of_interest->y + pan_y_change), -((GLfloat)camera->distance + (GLfloat)cam_distance_change)); //Translate along the z axis away from camera glRotatef((GLfloat)camera->twist + (GLfloat)twist_change, (GLfloat)0.0, (GLfloat)0.0, (GLfloat)1.0); //Rotate around z axis (usually by 0) glRotatef((GLfloat)camera->elevation + (GLfloat)elevation_change, (GLfloat)1.0, (GLfloat)0.0, (GLfloat)0.0); //Rotate around x axis glRotatef((GLfloat)camera->azimuth + (GLfloat)azimuth_change, (GLfloat)0.0, (GLfloat)1.0, (GLfloat)0.0); //Rotate around y axis //Draw grid grid(); //Wireframe switching //If shaded mode, draw the model with shading, else only draw the wireframe if (shaded_mode){ //Setup polygon offset for drawing wire on shaded glPolygonOffset(1.0, 1.0); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glColor3f(1.0, 1.0, 1.0); //Draw the obj model draw_models(); glDisable(GL_POLYGON_OFFSET_FILL); //If show wireframe, render the wireframe on top of shaded object if (show_wireframe){ glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glColor3f(0.0, 0.0, 0.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); } } else { //Wireframe only glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); glDisable(GL_CULL_FACE); glColor3f(1.0, 1.0, 1.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE); } glutSwapBuffers(); } /** Sets the projection **/ static void set_projection() { glViewport(0, 0, (GLsizei) width, (GLsizei) height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Perspective mode or ortho float aspect_ratio = (float)width / (float)height; if (camera->perspective_mode){ gluPerspective(camera->fov, GLfloat(aspect_ratio), camera->near_plane, camera->far_plane); } else { //Keep aspect ratio float left, right, bottom, top, temp_ortho_zoom; temp_ortho_zoom = camera->ortho_zoom + ortho_zoom_change; if (aspect_ratio < 1.0){ left = -temp_ortho_zoom; right = temp_ortho_zoom; bottom = -temp_ortho_zoom * ( 1.0f / aspect_ratio ); top = temp_ortho_zoom * ( 1.0f / aspect_ratio ); } else { left = -temp_ortho_zoom * aspect_ratio; right = temp_ortho_zoom * aspect_ratio; bottom = -temp_ortho_zoom; top = temp_ortho_zoom; } glOrtho(left, right, bottom, top, -camera->far_plane, camera->far_plane); } } /** Reshape function **/ static void reshape(int new_width, int new_height) { //Set Global Variables width = new_width; height = new_height; set_projection(); } /** Keyboard Input **/ static void keyboard_func(unsigned char key, int mx, int my) { switch (key) { //Camera Motion for Assignment case 'u': camera->point_of_interest->y -= 0.02f; glutPostRedisplay(); break; case 'd': camera->point_of_interest->y += 0.02f; glutPostRedisplay(); break; case 'l': camera->point_of_interest->x -= 0.02f; glutPostRedisplay(); break; case 'r': camera->point_of_interest->x += 0.02f; glutPostRedisplay(); break; case 'f': camera->distance -= 0.2f; glutPostRedisplay(); break; case 'b': camera->distance += 0.2f; glutPostRedisplay(); break; //Views case 'c': //Reset views //Destroy and reinitialize camera delete camera; camera = new PolarCamera(); set_projection(); break; case 'w': //Show Wireframe show_wireframe = show_wireframe == false ? true : false; break; case 's': //Shaded Model shaded_mode = shaded_mode == false ? true : false; break; case 'p': //Perspective camera->perspective_mode = true; set_projection(); break; case 'o': //Ortho camera->perspective_mode = false; set_projection(); break; case 'z': //Zoom forward if (camera->perspective_mode){ camera->fov -= 1.5f; } else { camera->ortho_zoom -= 0.1f; } set_projection(); break; case 'Z': //Zoom back if (camera->perspective_mode){ camera->fov += 1.5f; } else { camera->ortho_zoom += 0.1f; } set_projection(); break; //Alternative zoom case '+': //Zoom forward if (camera->perspective_mode){ camera->fov -= 1.5f; } else { camera->ortho_zoom -= 0.1f; } set_projection(); break; case '-': //Zoom back if (camera->perspective_mode){ camera->fov += 1.5f; } else { camera->ortho_zoom += 0.1f; } set_projection(); break; //Models case '1': model = 0; break; case '2': model = 1; break; case '3': model = 2; break; case '4': model = 3; break; case '5': model = 4; break; case '6': model = 5; break; case '7': model = 6; break; case '8': model = 7; break; //Exit case 27: exit(0); } glutPostRedisplay(); } /** Function Keys **/ static void functionKeys(int key, int mx, int my) { } /** Mouse Clicks **/ static void mouse_clicks(int button, int state, int mx, int my) { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) { left_mouse_down = true; //Set mouse down state to true mouse_down_x = mx; //Record screen position of mouse when user clicked left button mouse_down_y = my; //cout << "Left mouse button clicked at:" << mx << ", " << my << endl; } else { left_mouse_down = false; //Add changes to camera camera->azimuth += azimuth_change; camera->elevation += elevation_change; //Reset deltas azimuth_change = 0; elevation_change = 0; } break; case GLUT_RIGHT_BUTTON: //Move camera forward and back if (state == GLUT_DOWN) { right_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { right_mouse_down = false; //Reset distance deltas camera->distance += cam_distance_change; cam_distance_change = 0; //Ortho camera->ortho_zoom += ortho_zoom_change; ortho_zoom_change = 0; } break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_DOWN) { middle_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { middle_mouse_down = false; //Reset panning deltas camera->point_of_interest->x += pan_x_change; camera->point_of_interest->y += pan_y_change; pan_x_change = 0; pan_y_change = 0; } break; } } /** Mouse Movement **/ static void mouse_move(int mx, int my) { //Only bother processing if mouse button is pressed //Left Mouse Button - Orbit if (left_mouse_down){ azimuth_change = - (float(mouse_down_x) - float(mx)) / float(width) * 90; elevation_change = - (float(mouse_down_y) - float(my)) / float(height) * 90; } //Right Mouse Button - Dolly if (right_mouse_down){ if (camera->perspective_mode){ cam_distance_change = (float(mouse_down_x) - float(mx)) / float(width) * 10; } else { ortho_zoom_change = (float(mouse_down_x) - float(mx)) / float(width); set_projection(); } } //Middle Mouse Button - Panning if (middle_mouse_down){ pan_x_change = (float(mouse_down_x) - float(mx)) / float(width) * 5; pan_y_change = (float(mouse_down_y) - float(my)) / float(height) * 5; } //Force redisplay if (left_mouse_down || middle_mouse_down || right_mouse_down){ glutPostRedisplay(); } } /** Enable lighting & materials **/ static void lighting() { glShadeModel(GL_SMOOTH); //glShadeModel(GL_FLAT); //Setup Material GLfloat mat_ambient[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_diffuse[] = {(GLfloat)0.9, (GLfloat)0.9, (GLfloat)0.9, (GLfloat)1.0}; GLfloat mat_specular[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_shininess[] = {(GLfloat)50}; glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); //Setup Light(s) GLfloat light_position[] = {30.0, 30.0, 30.0, 0.0}; GLfloat white_light[] = {1.0, 1.0, 1.0, 1.0}; glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light); glLightfv(GL_LIGHT0, GL_SPECULAR, white_light); //Setup Ambient Light //GLfloat lmodel_ambient[] = {(GLfloat)0.2, (GLfloat)0.2, (GLfloat)0.2, (GLfloat)1.0}; //Turn on lighting glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); } //Load Texture static void load_texture(char* filename) { texture = new MyBitmap(filename); if (!texture->loaded){ cout << "Could not load texture." << endl; exit(0); } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &texName); //Allocate Texture Name glBindTexture(GL_TEXTURE_2D, texName); //Select current texture glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texture->width, texture->height, 0, GL_RGB, GL_UNSIGNED_BYTE, texture->data); glEnable( GL_TEXTURE_2D ); delete texture; } /** Clear out the screen **/ static void init() { //Load models uhtiger = new OBJModel("models/uhtiger.obj"); uhtiger->loadTexture("textures/uhtiger.bmp"); uhtiger->translate->z = 5.0f; m1abrams = new OBJModel("models/m1abrams.obj"); m1abrams->loadTexture("textures/M1_ABRAM.bmp"); m1abrams->translate->z = -5.0f; m1abrams->translate->x = -15.0f; humveehardtop = new OBJModel("models/humveehardtop.obj"); humveehardtop->loadTexture("textures/humveehardtop.bmp"); humveehardtop->translate->z = -5.0f; humveehardtop->translate->x = 15.0f; //Scene Graph rootNode = uhtiger; rootNode->addChild(humveehardtop); rootNode->addChild(m1abrams); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\quakeplasma.obj"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\uhtiger.obj"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\humveehardtop.obj"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\ussoldier1.obj"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\M1_ABRAM.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\plasma.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\uhtiger.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\humveehardtop.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\ussoldier01.bmp"); glClearColor(0.0, 0.0, 0.0, 0.0); //Set up lighting lighting(); //Anti-Aliasing - + /* glEnable (GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glLineWidth (1); - + */ //Backface culling glEnable(GL_CULL_FACE); } /** Main function **/ int main(int argc, char** argv) { - + + //Get current directory cout << "Firing up OBJViewer" << endl; cout << "===================" << endl << endl; cout << "Camera Motion " << endl; cout << "Orbit: Left click and drag mouse" << endl; cout << "Panning: Middle click and drag mouse" << endl; cout << "Dolly: Right click and drag mouse" << endl << endl; cout << "Viewport Controls " << endl; cout << "w: Toggle wireframe" << endl; cout << "s: Toggle shaded mode" << endl; cout << "p: Perspective mode" << endl; cout << "o: Orthographic mode" << endl; cout << "+ or z: Zoom in" << endl; cout << "- or Z(shift-z): Zoom out" << endl; cout << "c: Reset view" << endl << endl; - cout << "Deluxe Light Cycle Controls " << endl; - cout << "left/right arrow keys: Turn front wheels" << endl; - cout << "[ and ]: Open/close canopy" << endl << endl; - cout << "Escape: Quit" << endl; glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 100); glutCreateWindow("OBJViewer Test - Leonard Teo"); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard_func); glutSpecialFunc(functionKeys); glutMouseFunc(mouse_clicks); glutMotionFunc(mouse_move); glutMainLoop(); //Cleanup /* delete lightcycle_chassis; delete lightcycle_canopy; delete lightcycle_axel_front_right; delete lightcycle_axel_front_left; delete lightcycle_wheel_front_right; delete lightcycle_wheel_front_left; delete lightcycle_wheel_rear_right; delete lightcycle_wheel_rear_left; */ delete camera; exit(0); } \ No newline at end of file diff --git a/PolyMesh.cpp b/PolyMesh.cpp new file mode 100644 index 0000000..9d06267 --- /dev/null +++ b/PolyMesh.cpp @@ -0,0 +1,10 @@ +/* + * PolyMesh.cpp + * OBJViewer + * + * Created by Leonard Teo on 10-10-05. + * + */ + +#include "PolyMesh.h" + diff --git a/PolyMesh.h b/PolyMesh.h new file mode 100644 index 0000000..cc30852 --- /dev/null +++ b/PolyMesh.h @@ -0,0 +1,8 @@ +/* + * PolyMesh.h + * OBJViewer + * + * Created by Leonard Teo on 10-10-05. + * + */ + diff --git a/Vector3.cpp b/Vector3.cpp index 18bb15d..bc85de4 100644 --- a/Vector3.cpp +++ b/Vector3.cpp @@ -1,19 +1,20 @@ #include "Vector3.h" Vector3::Vector3(void) { x = 0; y = 0; z = 0; } Vector3::Vector3(float nx, float ny, float nz) { x = nx; y = ny; z = nz; } Vector3::~Vector3(void) { + delete this; }
leonardteo/OBJViewer
721f1a1c77cf1ba2fd8ce8e660a36e5d4c1d2078
Got Scene Graph working
diff --git a/Node.cpp b/Node.cpp index af0de09..5db8893 100644 --- a/Node.cpp +++ b/Node.cpp @@ -1,34 +1,37 @@ /* * Node.cpp * OBJViewer * * Created by Leonard Teo on 10-10-05. * */ #include "Node.h" //Constructor Node::Node() { - //this->children = new vector<Node*>; - + this->children = new vector<Node*>; this->scale = new Vector3(); this->rotate = new Vector3(); this->translate = new Vector3(); } //Destructor Node::~Node() { - //delete this->children; + delete this->children; delete this->scale; delete this->rotate; delete this->translate; } //Add a child void Node::addChild(Node* child) { this->children->push_back(child); -} \ No newline at end of file +} + +void Node::render() +{ +}; \ No newline at end of file diff --git a/OBJModel.cpp b/OBJModel.cpp index c4f4fb9..e7f450b 100644 --- a/OBJModel.cpp +++ b/OBJModel.cpp @@ -1,321 +1,324 @@ #include "OBJModel.h" using namespace std; //Constructor OBJModel::OBJModel(const char* fileName) { this->init(); this->load(fileName); } //Free memory OBJModel::~OBJModel(void) { delete this->vertices; delete this->normals; delete this->uvs; delete this->index; delete this->normalsIndex; delete this->uvIndex; } //General class initialization void OBJModel::init() { this->numVertices = 0; this->numFaces = 0; this->numUVs = 0; this->numNormals = 0; this->vertices = NULL; this->uvs = NULL; this->index = NULL; this->normals = NULL; this->uvIndex = NULL; this->type = POLYMESH; } void OBJModel::load(const char* fileName) { char buffer[255]; //Open file for reading ifstream file; file.open(fileName); if (!file.is_open()) { //If file isn't open cout << "Error loading file: " << fileName << endl; return; } else { //First pass of reading the file counts the data while ( !file.eof() ){ //Read the line file.getline(buffer, 255); //Read the line switch(buffer[0]) { //Vertex case 'v': switch(buffer[1]) { case ' ': this->numVertices++; break; case 'n': this->numNormals++; break; case 't': this->numUVs++; break; } break; //Face case 'f': this->numFaces++; break; default: break; } } //end of file //Echo the stats printf("fileName: %s \n", fileName); printf("Vertices: %d \n", this->numVertices); printf("Vertex Normals: %d \n", this->numNormals); printf("Faces: %d \n", this->numFaces); printf("\n"); //Allocate memory for data //Init vertices this->vertices = new Vector3*[this->numVertices]; this->index = new int*[this->numFaces]; //Triangles now //Init normals this->normals = new Vector3*[this->numNormals]; this->normalsIndex = new int*[this->numFaces]; //Triangles //Init UV's this->uvs = new UV*[this->numUVs]; this->uvIndex = new int*[this->numFaces]; //Initialize each of the indices for (int i=0; i<this->numFaces; i++){ this->index[i] = new int[3]; this->normalsIndex[i] = new int[3]; this->uvIndex[i] = new int[3]; for (int j=0; j<3; j++){ this->index[i][j] = 0; this->normalsIndex[i][j] = 0; this->uvIndex[i][j] = 0; } } //Second pass of file to load data file.clear(); //Clear eof status file.seekg(0, ios::beg); //Move cursor to beginning int currentVertex = 0; int currentIndex = 0; int currentNormal = 0; int currentUV = 0; int currentUVIndex = 0; int currentNormalIndex = 0; while (!file.eof()){ //Read line file.getline(buffer, 255); switch (buffer[0]){ //Vertex case 'v': switch(buffer[1]){ case ' ': //Create new vertex this->vertices[currentVertex] = new Vector3(); sscanf(buffer, "v %f %f %f", &this->vertices[currentVertex]->x, &this->vertices[currentVertex]->y, &this->vertices[currentVertex]->z); currentVertex++; break; case 'n': //Create new vertex normal this->normals[currentNormal] = new Vector3(); sscanf(buffer, "vn %f %f %f", &this->normals[currentNormal]->x, &this->normals[currentNormal]->y, &this->normals[currentNormal]->z); currentNormal++; break; case 't': //Create new UV this->uvs[currentUV] = new UV(); sscanf(buffer, "vt %f %f", &this->uvs[currentUV]->u, &this->uvs[currentUV]->v); currentUV++; break; } break; case 'f': //sscanf(buffer, "f %d/%*d/%d %d/%*d/%d %d/%*d/%d", &this->index[currentIndex][0], &this->normalsIndex[currentNormalIndex][0], &this->index[currentIndex][1], &this->normalsIndex[currentNormalIndex][1], &this->index[currentIndex][2], &this->normalsIndex[currentNormalIndex][2]); sscanf(buffer, "f %d/%d/%d %d/%d/%d %d/%d/%d", &this->index[currentIndex][0], &this->uvIndex[currentUVIndex][0], &this->normalsIndex[currentNormalIndex][0], &this->index[currentIndex][1], &this->uvIndex[currentUVIndex][1], &this->normalsIndex[currentNormalIndex][1], &this->index[currentIndex][2], &this->uvIndex[currentUVIndex][2], &this->normalsIndex[currentNormalIndex][2]); currentIndex++; currentNormalIndex++; currentUVIndex++; break; } } //end of file //Release file pointer file.close(); } //Debug - echo out all the vertices and faces /* printf("Vertices: \n"); for(int i=0; i< this->numVertices; i++) { printf(" %f %f %f \n", this->vertices[i]->x, this->vertices[i]->y, this->vertices[i]->z ); } printf("\n\nUV coordinates: \n"); for (int i=0; i< this->numUVs; i++) { printf(" %f %f \n", this->uvs[i]->u, this->uvs[i]->v); } printf("\n\nVertex Normals: \n"); for(int i=0; i< this->numNormals ; i++) { printf(" %f %f %f \n", this->normals[i]->x, this->normals[i]->y, this->normals[i]->z); } printf("\n\nIndex/UV/Normal: \n"); for(int i=0; i< this->numFaces; i++){ printf(" %d/%d/%d %d/%d/%d %d/%d/%d\n", this->index[i][0], this->uvIndex[i][0], this->normalsIndex[i][0], this->index[i][1], this->uvIndex[i][1], this->normalsIndex[i][1], this->index[i][2], this->uvIndex[i][2], this->normalsIndex[i][2]); } */ //decrement all indices to cater for OpenGL (OBJ indices start at 1) for(int i = 0; i < this->numFaces; i++) { for(int j=0; j<3; j++){ this->index[i][j]--; this->normalsIndex[i][j]--; this->uvIndex[i][j]--; } } } void OBJModel::render() { - + for (int i=0; i<this->children->size(); i++) + { + this->children->at(i)->render(); + } //Draw this glPushMatrix(); glTranslatef((GLfloat)this->translate->x, (GLfloat)this->translate->y, (GLfloat)this->translate->z); this->draw(); glPopMatrix(); } /** Drawing routine **/ void OBJModel::draw() { //Load texture glBindTexture(GL_TEXTURE_2D, this->texture); //For each face, draw a Triangle glBegin(GL_TRIANGLES); for (int face = 0; face < this->numFaces; face++) { //Draw the vertex at each of the vertex numbders glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][0]]->u, (GLfloat)this->uvs[this->uvIndex[face][0]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][0]]->x, (GLfloat)this->normals[this->normalsIndex[face][0]]->y, (GLfloat)this->normals[this->normalsIndex[face][0]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][0]]->x, (GLfloat)this->vertices[this->index[face][0]]->y, (GLfloat)this->vertices[this->index[face][0]]->z); glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][1]]->u, (GLfloat)this->uvs[this->uvIndex[face][1]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][1]]->x, (GLfloat)this->normals[this->normalsIndex[face][1]]->y, (GLfloat)this->normals[this->normalsIndex[face][1]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][1]]->x, (GLfloat)this->vertices[this->index[face][1]]->y, (GLfloat)this->vertices[this->index[face][1]]->z); glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][2]]->u, (GLfloat)this->uvs[this->uvIndex[face][2]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][2]]->x, (GLfloat)this->normals[this->normalsIndex[face][2]]->y, (GLfloat)this->normals[this->normalsIndex[face][2]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][2]]->x, (GLfloat)this->vertices[this->index[face][2]]->y, (GLfloat)this->vertices[this->index[face][2]]->z); /* Non-Optimized code for debugging //Get vertex numbers int v1, v2, v3; v1 = this->index[face][0]; v2 = this->index[face][1]; v3 = this->index[face][2]; //Get Normal numbers int n1, n2, n3; n1 = this->normalsIndex[face][0]; n2 = this->normalsIndex[face][1]; n3 = this->normalsIndex[face][2]; //Get UVs int uv1, uv2, uv3; uv1 = this->uvIndex[face][0]; uv2 = this->uvIndex[face][1]; uv3 = this->uvIndex[face][2]; //Draw the vertex at each of the vertex numbders glTexCoord2f((GLfloat)this->uvs[uv1]->u, (GLfloat)this->uvs[uv1]->v); glNormal3f((GLfloat)this->normals[n1]->x, (GLfloat)this->normals[n1]->y, (GLfloat)this->normals[n1]->z); glVertex3f((GLfloat)this->vertices[v1]->x, (GLfloat)this->vertices[v1]->y, (GLfloat)this->vertices[v1]->z); glTexCoord2f((GLfloat)this->uvs[uv2]->u, (GLfloat)this->uvs[uv2]->v); glNormal3f((GLfloat)this->normals[n2]->x, (GLfloat)this->normals[n2]->y, (GLfloat)this->normals[n2]->z); glVertex3f((GLfloat)this->vertices[v2]->x, (GLfloat)this->vertices[v2]->y, (GLfloat)this->vertices[v2]->z); glTexCoord2f((GLfloat)this->uvs[uv3]->u, (GLfloat)this->uvs[uv3]->v); glNormal3f((GLfloat)this->normals[n3]->x, (GLfloat)this->normals[n3]->y, (GLfloat)this->normals[n3]->z); glVertex3f((GLfloat)this->vertices[v3]->x, (GLfloat)this->vertices[v3]->y, (GLfloat)this->vertices[v3]->z); */ } glEnd(); glFlush(); } /*** Load Texture ***/ void OBJModel::loadTexture(const char* fileName) { this->image = new MyBitmap(fileName); if (!image->loaded){ cout << "Could not load texture." << endl; exit(0); } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &this->texture); //Allocate Texture Name glBindTexture(GL_TEXTURE_2D, this->texture); //Select current texture glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->image->width, this->image->height, 0, GL_RGB, GL_UNSIGNED_BYTE, this->image->data); glEnable( GL_TEXTURE_2D ); delete image; } \ No newline at end of file diff --git a/OBJViewer.cpp b/OBJViewer.cpp index 842f40a..2af7fae 100644 --- a/OBJViewer.cpp +++ b/OBJViewer.cpp @@ -88,622 +88,625 @@ Node* rootNode; Draw a 24x24 grid **/ static void grid(int scale = 1) { //Turn off lighting for grid glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); //Start drawing lines glBegin(GL_LINES); glColor3f(0.5, 0.5, 0.5); for (int x=-12; x<=12; x++){ if (x != 0){ glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(-12*scale)); glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(12*scale)); } } for (int z=-12; z<=12; z++){ if (z != 0){ glVertex3f((GLfloat)(-12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); glVertex3f((GLfloat)(12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); } } glEnd(); //Make sure the lines at the origin are nice and different glBegin(GL_LINES); glColor3f(0.75, 0.75, 0.75); glVertex3f(0, 0, (GLfloat)(-12*scale)); glVertex3f(0, 0, (GLfloat)(12*scale)); glVertex3f((GLfloat)(-12*scale), 0, 0); glVertex3f((GLfloat)(12*scale), 0, 0); glEnd(); glFlush(); //Turn lighting back on glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); } static void draw_models() { //Draw using scene graph rootNode->render(); //Draw all three models (let's be awesome) /* glPushMatrix(); glTranslatef(-15, 0, 0); m1abrams->draw(); glPopMatrix(); uhtiger->draw(); glPushMatrix(); glTranslatef(15,0,0); humveehardtop->draw(); glPopMatrix(); */ //Switch model /* switch (model) { case 0: m1abrams->draw(); break; case 1: humveehardtop->draw(); break; case 2: uhtiger->draw(); break; } */ } /** Display function **/ static void display() { //Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); /** Camera setup **/ //Translate & Rotate Polar Views glTranslatef(-(GLfloat)(camera->point_of_interest->x + pan_x_change), (GLfloat)(camera->point_of_interest->y + pan_y_change), -((GLfloat)camera->distance + (GLfloat)cam_distance_change)); //Translate along the z axis away from camera glRotatef((GLfloat)camera->twist + (GLfloat)twist_change, (GLfloat)0.0, (GLfloat)0.0, (GLfloat)1.0); //Rotate around z axis (usually by 0) glRotatef((GLfloat)camera->elevation + (GLfloat)elevation_change, (GLfloat)1.0, (GLfloat)0.0, (GLfloat)0.0); //Rotate around x axis glRotatef((GLfloat)camera->azimuth + (GLfloat)azimuth_change, (GLfloat)0.0, (GLfloat)1.0, (GLfloat)0.0); //Rotate around y axis //Draw grid grid(); //Wireframe switching //If shaded mode, draw the model with shading, else only draw the wireframe if (shaded_mode){ //Setup polygon offset for drawing wire on shaded glPolygonOffset(1.0, 1.0); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glColor3f(1.0, 1.0, 1.0); //Draw the obj model draw_models(); glDisable(GL_POLYGON_OFFSET_FILL); //If show wireframe, render the wireframe on top of shaded object if (show_wireframe){ glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glColor3f(0.0, 0.0, 0.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); } } else { //Wireframe only glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); glDisable(GL_CULL_FACE); glColor3f(1.0, 1.0, 1.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE); } glutSwapBuffers(); } /** Sets the projection **/ static void set_projection() { glViewport(0, 0, (GLsizei) width, (GLsizei) height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Perspective mode or ortho float aspect_ratio = (float)width / (float)height; if (camera->perspective_mode){ gluPerspective(camera->fov, GLfloat(aspect_ratio), camera->near_plane, camera->far_plane); } else { //Keep aspect ratio float left, right, bottom, top, temp_ortho_zoom; temp_ortho_zoom = camera->ortho_zoom + ortho_zoom_change; if (aspect_ratio < 1.0){ left = -temp_ortho_zoom; right = temp_ortho_zoom; bottom = -temp_ortho_zoom * ( 1.0f / aspect_ratio ); top = temp_ortho_zoom * ( 1.0f / aspect_ratio ); } else { left = -temp_ortho_zoom * aspect_ratio; right = temp_ortho_zoom * aspect_ratio; bottom = -temp_ortho_zoom; top = temp_ortho_zoom; } glOrtho(left, right, bottom, top, -camera->far_plane, camera->far_plane); } } /** Reshape function **/ static void reshape(int new_width, int new_height) { //Set Global Variables width = new_width; height = new_height; set_projection(); } /** Keyboard Input **/ static void keyboard_func(unsigned char key, int mx, int my) { switch (key) { //Camera Motion for Assignment case 'u': camera->point_of_interest->y -= 0.02f; glutPostRedisplay(); break; case 'd': camera->point_of_interest->y += 0.02f; glutPostRedisplay(); break; case 'l': camera->point_of_interest->x -= 0.02f; glutPostRedisplay(); break; case 'r': camera->point_of_interest->x += 0.02f; glutPostRedisplay(); break; case 'f': camera->distance -= 0.2f; glutPostRedisplay(); break; case 'b': camera->distance += 0.2f; glutPostRedisplay(); break; //Views case 'c': //Reset views //Destroy and reinitialize camera delete camera; camera = new PolarCamera(); set_projection(); break; case 'w': //Show Wireframe show_wireframe = show_wireframe == false ? true : false; break; case 's': //Shaded Model shaded_mode = shaded_mode == false ? true : false; break; case 'p': //Perspective camera->perspective_mode = true; set_projection(); break; case 'o': //Ortho camera->perspective_mode = false; set_projection(); break; case 'z': //Zoom forward if (camera->perspective_mode){ camera->fov -= 1.5f; } else { camera->ortho_zoom -= 0.1f; } set_projection(); break; case 'Z': //Zoom back if (camera->perspective_mode){ camera->fov += 1.5f; } else { camera->ortho_zoom += 0.1f; } set_projection(); break; //Alternative zoom case '+': //Zoom forward if (camera->perspective_mode){ camera->fov -= 1.5f; } else { camera->ortho_zoom -= 0.1f; } set_projection(); break; case '-': //Zoom back if (camera->perspective_mode){ camera->fov += 1.5f; } else { camera->ortho_zoom += 0.1f; } set_projection(); break; //Models case '1': model = 0; break; case '2': model = 1; break; case '3': model = 2; break; case '4': model = 3; break; case '5': model = 4; break; case '6': model = 5; break; case '7': model = 6; break; case '8': model = 7; break; //Exit case 27: exit(0); } glutPostRedisplay(); } /** Function Keys **/ static void functionKeys(int key, int mx, int my) { } /** Mouse Clicks **/ static void mouse_clicks(int button, int state, int mx, int my) { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) { left_mouse_down = true; //Set mouse down state to true mouse_down_x = mx; //Record screen position of mouse when user clicked left button mouse_down_y = my; //cout << "Left mouse button clicked at:" << mx << ", " << my << endl; } else { left_mouse_down = false; //Add changes to camera camera->azimuth += azimuth_change; camera->elevation += elevation_change; //Reset deltas azimuth_change = 0; elevation_change = 0; } break; case GLUT_RIGHT_BUTTON: //Move camera forward and back if (state == GLUT_DOWN) { right_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { right_mouse_down = false; //Reset distance deltas camera->distance += cam_distance_change; cam_distance_change = 0; //Ortho camera->ortho_zoom += ortho_zoom_change; ortho_zoom_change = 0; } break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_DOWN) { middle_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { middle_mouse_down = false; //Reset panning deltas camera->point_of_interest->x += pan_x_change; camera->point_of_interest->y += pan_y_change; pan_x_change = 0; pan_y_change = 0; } break; } } /** Mouse Movement **/ static void mouse_move(int mx, int my) { //Only bother processing if mouse button is pressed //Left Mouse Button - Orbit if (left_mouse_down){ azimuth_change = - (float(mouse_down_x) - float(mx)) / float(width) * 90; elevation_change = - (float(mouse_down_y) - float(my)) / float(height) * 90; } //Right Mouse Button - Dolly if (right_mouse_down){ if (camera->perspective_mode){ cam_distance_change = (float(mouse_down_x) - float(mx)) / float(width) * 10; } else { ortho_zoom_change = (float(mouse_down_x) - float(mx)) / float(width); set_projection(); } } //Middle Mouse Button - Panning if (middle_mouse_down){ pan_x_change = (float(mouse_down_x) - float(mx)) / float(width) * 5; pan_y_change = (float(mouse_down_y) - float(my)) / float(height) * 5; } //Force redisplay if (left_mouse_down || middle_mouse_down || right_mouse_down){ glutPostRedisplay(); } } /** Enable lighting & materials **/ static void lighting() { glShadeModel(GL_SMOOTH); //glShadeModel(GL_FLAT); //Setup Material GLfloat mat_ambient[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_diffuse[] = {(GLfloat)0.9, (GLfloat)0.9, (GLfloat)0.9, (GLfloat)1.0}; GLfloat mat_specular[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_shininess[] = {(GLfloat)50}; glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); //Setup Light(s) GLfloat light_position[] = {30.0, 30.0, 30.0, 0.0}; GLfloat white_light[] = {1.0, 1.0, 1.0, 1.0}; glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light); glLightfv(GL_LIGHT0, GL_SPECULAR, white_light); //Setup Ambient Light //GLfloat lmodel_ambient[] = {(GLfloat)0.2, (GLfloat)0.2, (GLfloat)0.2, (GLfloat)1.0}; //Turn on lighting glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); } //Load Texture static void load_texture(char* filename) { texture = new MyBitmap(filename); if (!texture->loaded){ cout << "Could not load texture." << endl; exit(0); } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &texName); //Allocate Texture Name glBindTexture(GL_TEXTURE_2D, texName); //Select current texture glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texture->width, texture->height, 0, GL_RGB, GL_UNSIGNED_BYTE, texture->data); glEnable( GL_TEXTURE_2D ); delete texture; } /** Clear out the screen **/ static void init() { //Load models + uhtiger = new OBJModel("models/uhtiger.obj"); + uhtiger->loadTexture("textures/uhtiger.bmp"); + uhtiger->translate->z = 5.0f; + m1abrams = new OBJModel("models/m1abrams.obj"); m1abrams->loadTexture("textures/M1_ABRAM.bmp"); + m1abrams->translate->z = -5.0f; + m1abrams->translate->x = -15.0f; humveehardtop = new OBJModel("models/humveehardtop.obj"); humveehardtop->loadTexture("textures/humveehardtop.bmp"); - humveehardtop->translate->x = -15.0f; - - uhtiger = new OBJModel("models/uhtiger.obj"); - uhtiger->loadTexture("textures/uhtiger.bmp"); - uhtiger->translate->x = 15.0f; + humveehardtop->translate->z = -5.0f; + humveehardtop->translate->x = 15.0f; //Scene Graph - rootNode = m1abrams; - m1abrams->addChild(humveehardtop); - m1abrams->addChild(uhtiger); + rootNode = uhtiger; + rootNode->addChild(humveehardtop); + rootNode->addChild(m1abrams); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\quakeplasma.obj"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\uhtiger.obj"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\humveehardtop.obj"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\ussoldier1.obj"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\M1_ABRAM.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\plasma.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\uhtiger.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\humveehardtop.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\ussoldier01.bmp"); glClearColor(0.0, 0.0, 0.0, 0.0); //Set up lighting lighting(); //Anti-Aliasing glEnable (GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glLineWidth (1); //Backface culling glEnable(GL_CULL_FACE); } /** Main function **/ int main(int argc, char** argv) { cout << "Firing up OBJViewer" << endl; cout << "===================" << endl << endl; cout << "Camera Motion " << endl; cout << "Orbit: Left click and drag mouse" << endl; cout << "Panning: Middle click and drag mouse" << endl; cout << "Dolly: Right click and drag mouse" << endl << endl; cout << "Viewport Controls " << endl; cout << "w: Toggle wireframe" << endl; cout << "s: Toggle shaded mode" << endl; cout << "p: Perspective mode" << endl; cout << "o: Orthographic mode" << endl; cout << "+ or z: Zoom in" << endl; cout << "- or Z(shift-z): Zoom out" << endl; cout << "c: Reset view" << endl << endl; cout << "Deluxe Light Cycle Controls " << endl; cout << "left/right arrow keys: Turn front wheels" << endl; cout << "[ and ]: Open/close canopy" << endl << endl; cout << "Escape: Quit" << endl; glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 100); glutCreateWindow("OBJViewer Test - Leonard Teo"); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard_func); glutSpecialFunc(functionKeys); glutMouseFunc(mouse_clicks); glutMotionFunc(mouse_move); glutMainLoop(); //Cleanup /* delete lightcycle_chassis; delete lightcycle_canopy; delete lightcycle_axel_front_right; delete lightcycle_axel_front_left; delete lightcycle_wheel_front_right; delete lightcycle_wheel_front_left; delete lightcycle_wheel_rear_right; delete lightcycle_wheel_rear_left; */ delete camera; exit(0); } \ No newline at end of file
leonardteo/OBJViewer
88852d188aa80ab4e0ec95c07081182545e98ede
Some Mac enhancements
diff --git a/OBJModel.cpp b/OBJModel.cpp index 7a7d076..a9ac9eb 100644 --- a/OBJModel.cpp +++ b/OBJModel.cpp @@ -1,305 +1,305 @@ #include "OBJModel.h" using namespace std; //Constructor OBJModel::OBJModel(const char* fileName) { this->init(); this->load(fileName); } //Free memory OBJModel::~OBJModel(void) { delete this->vertices; delete this->normals; delete this->uvs; delete this->index; delete this->normalsIndex; delete this->uvIndex; } //General class initialization void OBJModel::init() { this->numVertices = 0; this->numFaces = 0; this->numUVs = 0; this->numNormals = 0; this->vertices = NULL; this->uvs = NULL; this->index = NULL; this->normals = NULL; this->uvIndex = NULL; } void OBJModel::load(const char* fileName) { char buffer[255]; //Open file for reading ifstream file; file.open(fileName); if (!file.is_open()) { //If file isn't open cout << "Error loading file: " << fileName << endl; return; } else { //First pass of reading the file counts the data while ( !file.eof() ){ //Read the line file.getline(buffer, 255); //Read the line switch(buffer[0]) { //Vertex case 'v': switch(buffer[1]) { case ' ': this->numVertices++; break; case 'n': this->numNormals++; break; case 't': this->numUVs++; break; } break; //Face case 'f': this->numFaces++; break; default: break; } } //end of file //Echo the stats printf("fileName: %s \n", fileName); printf("Vertices: %d \n", this->numVertices); printf("Vertex Normals: %d \n", this->numNormals); printf("Faces: %d \n", this->numFaces); printf("\n"); //Allocate memory for data //Init vertices this->vertices = new Vector3*[this->numVertices]; this->index = new int*[this->numFaces]; //Triangles now //Init normals this->normals = new Vector3*[this->numNormals]; this->normalsIndex = new int*[this->numFaces]; //Triangles //Init UV's this->uvs = new UV*[this->numUVs]; this->uvIndex = new int*[this->numFaces]; //Initialize each of the indices for (int i=0; i<this->numFaces; i++){ this->index[i] = new int[3]; this->normalsIndex[i] = new int[3]; this->uvIndex[i] = new int[3]; for (int j=0; j<3; j++){ this->index[i][j] = 0; this->normalsIndex[i][j] = 0; this->uvIndex[i][j] = 0; } } //Second pass of file to load data file.clear(); //Clear eof status file.seekg(0, ios::beg); //Move cursor to beginning int currentVertex = 0; int currentIndex = 0; int currentNormal = 0; int currentUV = 0; int currentUVIndex = 0; int currentNormalIndex = 0; while (!file.eof()){ //Read line file.getline(buffer, 255); switch (buffer[0]){ //Vertex case 'v': switch(buffer[1]){ case ' ': //Create new vertex this->vertices[currentVertex] = new Vector3(); sscanf(buffer, "v %f %f %f", &this->vertices[currentVertex]->x, &this->vertices[currentVertex]->y, &this->vertices[currentVertex]->z); currentVertex++; break; case 'n': //Create new vertex normal this->normals[currentNormal] = new Vector3(); sscanf(buffer, "vn %f %f %f", &this->normals[currentNormal]->x, &this->normals[currentNormal]->y, &this->normals[currentNormal]->z); currentNormal++; break; case 't': //Create new UV this->uvs[currentUV] = new UV(); sscanf(buffer, "vt %f %f", &this->uvs[currentUV]->u, &this->uvs[currentUV]->v); currentUV++; break; } break; case 'f': //sscanf(buffer, "f %d/%*d/%d %d/%*d/%d %d/%*d/%d", &this->index[currentIndex][0], &this->normalsIndex[currentNormalIndex][0], &this->index[currentIndex][1], &this->normalsIndex[currentNormalIndex][1], &this->index[currentIndex][2], &this->normalsIndex[currentNormalIndex][2]); sscanf(buffer, "f %d/%d/%d %d/%d/%d %d/%d/%d", &this->index[currentIndex][0], &this->uvIndex[currentUVIndex][0], &this->normalsIndex[currentNormalIndex][0], &this->index[currentIndex][1], &this->uvIndex[currentUVIndex][1], &this->normalsIndex[currentNormalIndex][1], &this->index[currentIndex][2], &this->uvIndex[currentUVIndex][2], &this->normalsIndex[currentNormalIndex][2]); currentIndex++; currentNormalIndex++; currentUVIndex++; break; } } //end of file //Release file pointer file.close(); } //Debug - echo out all the vertices and faces /* printf("Vertices: \n"); for(int i=0; i< this->numVertices; i++) { printf(" %f %f %f \n", this->vertices[i]->x, this->vertices[i]->y, this->vertices[i]->z ); } printf("\n\nUV coordinates: \n"); for (int i=0; i< this->numUVs; i++) { printf(" %f %f \n", this->uvs[i]->u, this->uvs[i]->v); } printf("\n\nVertex Normals: \n"); for(int i=0; i< this->numNormals ; i++) { printf(" %f %f %f \n", this->normals[i]->x, this->normals[i]->y, this->normals[i]->z); } printf("\n\nIndex/UV/Normal: \n"); for(int i=0; i< this->numFaces; i++){ printf(" %d/%d/%d %d/%d/%d %d/%d/%d\n", this->index[i][0], this->uvIndex[i][0], this->normalsIndex[i][0], this->index[i][1], this->uvIndex[i][1], this->normalsIndex[i][1], this->index[i][2], this->uvIndex[i][2], this->normalsIndex[i][2]); } */ //decrement all indices to cater for OpenGL (OBJ indices start at 1) for(int i = 0; i < this->numFaces; i++) { for(int j=0; j<3; j++){ this->index[i][j]--; this->normalsIndex[i][j]--; this->uvIndex[i][j]--; } } } /** Drawing routine **/ void OBJModel::draw() { //Load texture glBindTexture(GL_TEXTURE_2D, this->texture); - //For each face, draw a quad + //For each face, draw a Triangle glBegin(GL_TRIANGLES); for (int face = 0; face < this->numFaces; face++) { //Draw the vertex at each of the vertex numbders glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][0]]->u, (GLfloat)this->uvs[this->uvIndex[face][0]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][0]]->x, (GLfloat)this->normals[this->normalsIndex[face][0]]->y, (GLfloat)this->normals[this->normalsIndex[face][0]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][0]]->x, (GLfloat)this->vertices[this->index[face][0]]->y, (GLfloat)this->vertices[this->index[face][0]]->z); glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][1]]->u, (GLfloat)this->uvs[this->uvIndex[face][1]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][1]]->x, (GLfloat)this->normals[this->normalsIndex[face][1]]->y, (GLfloat)this->normals[this->normalsIndex[face][1]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][1]]->x, (GLfloat)this->vertices[this->index[face][1]]->y, (GLfloat)this->vertices[this->index[face][1]]->z); glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][2]]->u, (GLfloat)this->uvs[this->uvIndex[face][2]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][2]]->x, (GLfloat)this->normals[this->normalsIndex[face][2]]->y, (GLfloat)this->normals[this->normalsIndex[face][2]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][2]]->x, (GLfloat)this->vertices[this->index[face][2]]->y, (GLfloat)this->vertices[this->index[face][2]]->z); /* Non-Optimized code for debugging //Get vertex numbers int v1, v2, v3; v1 = this->index[face][0]; v2 = this->index[face][1]; v3 = this->index[face][2]; //Get Normal numbers int n1, n2, n3; n1 = this->normalsIndex[face][0]; n2 = this->normalsIndex[face][1]; n3 = this->normalsIndex[face][2]; //Get UVs int uv1, uv2, uv3; uv1 = this->uvIndex[face][0]; uv2 = this->uvIndex[face][1]; uv3 = this->uvIndex[face][2]; //Draw the vertex at each of the vertex numbders glTexCoord2f((GLfloat)this->uvs[uv1]->u, (GLfloat)this->uvs[uv1]->v); glNormal3f((GLfloat)this->normals[n1]->x, (GLfloat)this->normals[n1]->y, (GLfloat)this->normals[n1]->z); glVertex3f((GLfloat)this->vertices[v1]->x, (GLfloat)this->vertices[v1]->y, (GLfloat)this->vertices[v1]->z); glTexCoord2f((GLfloat)this->uvs[uv2]->u, (GLfloat)this->uvs[uv2]->v); glNormal3f((GLfloat)this->normals[n2]->x, (GLfloat)this->normals[n2]->y, (GLfloat)this->normals[n2]->z); glVertex3f((GLfloat)this->vertices[v2]->x, (GLfloat)this->vertices[v2]->y, (GLfloat)this->vertices[v2]->z); glTexCoord2f((GLfloat)this->uvs[uv3]->u, (GLfloat)this->uvs[uv3]->v); glNormal3f((GLfloat)this->normals[n3]->x, (GLfloat)this->normals[n3]->y, (GLfloat)this->normals[n3]->z); glVertex3f((GLfloat)this->vertices[v3]->x, (GLfloat)this->vertices[v3]->y, (GLfloat)this->vertices[v3]->z); */ } glEnd(); glFlush(); } /*** Load Texture ***/ void OBJModel::loadTexture(const char* fileName) { this->image = new MyBitmap(fileName); if (!image->loaded){ cout << "Could not load texture." << endl; exit(0); } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &this->texture); //Allocate Texture Name glBindTexture(GL_TEXTURE_2D, this->texture); //Select current texture glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->image->width, this->image->height, 0, GL_RGB, GL_UNSIGNED_BYTE, this->image->data); glEnable( GL_TEXTURE_2D ); delete image; } \ No newline at end of file diff --git a/OBJViewer.cpp b/OBJViewer.cpp index bcbeb29..ec1d29c 100644 --- a/OBJViewer.cpp +++ b/OBJViewer.cpp @@ -105,589 +105,589 @@ static void grid(int scale = 1) glVertex3f((GLfloat)(-12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); glVertex3f((GLfloat)(12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); } } glEnd(); //Make sure the lines at the origin are nice and different glBegin(GL_LINES); glColor3f(0.75, 0.75, 0.75); glVertex3f(0, 0, (GLfloat)(-12*scale)); glVertex3f(0, 0, (GLfloat)(12*scale)); glVertex3f((GLfloat)(-12*scale), 0, 0); glVertex3f((GLfloat)(12*scale), 0, 0); glEnd(); glFlush(); //Turn lighting back on glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); } static void draw_models() { //Draw all three models (let's be awesome) glPushMatrix(); glTranslatef(-15, 0, 0); m1abrams->draw(); glPopMatrix(); uhtiger->draw(); glPushMatrix(); glTranslatef(15,0,0); humveehardtop->draw(); glPopMatrix(); //Switch model /* switch (model) { case 0: m1abrams->draw(); break; case 1: humveehardtop->draw(); break; case 2: uhtiger->draw(); break; } */ } /** Display function **/ static void display() { //Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); /** Camera setup **/ //Translate & Rotate Polar Views glTranslatef(-(GLfloat)(camera->point_of_interest->x + pan_x_change), (GLfloat)(camera->point_of_interest->y + pan_y_change), -((GLfloat)camera->distance + (GLfloat)cam_distance_change)); //Translate along the z axis away from camera glRotatef((GLfloat)camera->twist + (GLfloat)twist_change, (GLfloat)0.0, (GLfloat)0.0, (GLfloat)1.0); //Rotate around z axis (usually by 0) glRotatef((GLfloat)camera->elevation + (GLfloat)elevation_change, (GLfloat)1.0, (GLfloat)0.0, (GLfloat)0.0); //Rotate around x axis glRotatef((GLfloat)camera->azimuth + (GLfloat)azimuth_change, (GLfloat)0.0, (GLfloat)1.0, (GLfloat)0.0); //Rotate around y axis //Draw grid grid(); //Wireframe switching //If shaded mode, draw the model with shading, else only draw the wireframe if (shaded_mode){ //Setup polygon offset for drawing wire on shaded glPolygonOffset(1.0, 1.0); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glColor3f(1.0, 1.0, 1.0); //Draw the obj model draw_models(); glDisable(GL_POLYGON_OFFSET_FILL); //If show wireframe, render the wireframe on top of shaded object if (show_wireframe){ glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glColor3f(0.0, 0.0, 0.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); } } else { //Wireframe only glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); glDisable(GL_CULL_FACE); glColor3f(1.0, 1.0, 1.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE); } glutSwapBuffers(); } /** Sets the projection **/ static void set_projection() { glViewport(0, 0, (GLsizei) width, (GLsizei) height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Perspective mode or ortho float aspect_ratio = (float)width / (float)height; if (camera->perspective_mode){ gluPerspective(camera->fov, GLfloat(aspect_ratio), camera->near_plane, camera->far_plane); } else { //Keep aspect ratio float left, right, bottom, top, temp_ortho_zoom; temp_ortho_zoom = camera->ortho_zoom + ortho_zoom_change; if (aspect_ratio < 1.0){ left = -temp_ortho_zoom; right = temp_ortho_zoom; bottom = -temp_ortho_zoom * ( 1.0f / aspect_ratio ); top = temp_ortho_zoom * ( 1.0f / aspect_ratio ); } else { left = -temp_ortho_zoom * aspect_ratio; right = temp_ortho_zoom * aspect_ratio; bottom = -temp_ortho_zoom; top = temp_ortho_zoom; } glOrtho(left, right, bottom, top, -camera->far_plane, camera->far_plane); } } /** Reshape function **/ static void reshape(int new_width, int new_height) { //Set Global Variables width = new_width; height = new_height; set_projection(); } /** Keyboard Input **/ static void keyboard_func(unsigned char key, int mx, int my) { switch (key) { //Camera Motion for Assignment case 'u': camera->point_of_interest->y -= 0.02f; glutPostRedisplay(); break; case 'd': camera->point_of_interest->y += 0.02f; glutPostRedisplay(); break; case 'l': camera->point_of_interest->x -= 0.02f; glutPostRedisplay(); break; case 'r': camera->point_of_interest->x += 0.02f; glutPostRedisplay(); break; case 'f': camera->distance -= 0.2f; glutPostRedisplay(); break; case 'b': camera->distance += 0.2f; glutPostRedisplay(); break; //Views case 'c': //Reset views //Destroy and reinitialize camera delete camera; camera = new PolarCamera(); set_projection(); break; case 'w': //Show Wireframe show_wireframe = show_wireframe == false ? true : false; break; case 's': //Shaded Model shaded_mode = shaded_mode == false ? true : false; break; case 'p': //Perspective camera->perspective_mode = true; set_projection(); break; case 'o': //Ortho camera->perspective_mode = false; set_projection(); break; case 'z': //Zoom forward if (camera->perspective_mode){ camera->fov -= 1.5f; } else { camera->ortho_zoom -= 0.1f; } set_projection(); break; case 'Z': //Zoom back if (camera->perspective_mode){ camera->fov += 1.5f; } else { camera->ortho_zoom += 0.1f; } set_projection(); break; //Alternative zoom case '+': //Zoom forward if (camera->perspective_mode){ camera->fov -= 1.5f; } else { camera->ortho_zoom -= 0.1f; } set_projection(); break; case '-': //Zoom back if (camera->perspective_mode){ camera->fov += 1.5f; } else { camera->ortho_zoom += 0.1f; } set_projection(); break; //Models case '1': model = 0; break; case '2': model = 1; break; case '3': model = 2; break; case '4': model = 3; break; case '5': model = 4; break; case '6': model = 5; break; case '7': model = 6; break; case '8': model = 7; break; //Exit case 27: exit(0); } glutPostRedisplay(); } /** Function Keys **/ static void functionKeys(int key, int mx, int my) { } /** Mouse Clicks **/ static void mouse_clicks(int button, int state, int mx, int my) { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) { left_mouse_down = true; //Set mouse down state to true mouse_down_x = mx; //Record screen position of mouse when user clicked left button mouse_down_y = my; //cout << "Left mouse button clicked at:" << mx << ", " << my << endl; } else { left_mouse_down = false; //Add changes to camera camera->azimuth += azimuth_change; camera->elevation += elevation_change; //Reset deltas azimuth_change = 0; elevation_change = 0; } break; case GLUT_RIGHT_BUTTON: //Move camera forward and back if (state == GLUT_DOWN) { right_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { right_mouse_down = false; //Reset distance deltas camera->distance += cam_distance_change; cam_distance_change = 0; //Ortho camera->ortho_zoom += ortho_zoom_change; ortho_zoom_change = 0; } break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_DOWN) { middle_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { middle_mouse_down = false; //Reset panning deltas camera->point_of_interest->x += pan_x_change; camera->point_of_interest->y += pan_y_change; pan_x_change = 0; pan_y_change = 0; } break; } } /** Mouse Movement **/ static void mouse_move(int mx, int my) { //Only bother processing if mouse button is pressed //Left Mouse Button - Orbit if (left_mouse_down){ azimuth_change = - (float(mouse_down_x) - float(mx)) / float(width) * 90; elevation_change = - (float(mouse_down_y) - float(my)) / float(height) * 90; } //Right Mouse Button - Dolly if (right_mouse_down){ if (camera->perspective_mode){ cam_distance_change = (float(mouse_down_x) - float(mx)) / float(width) * 10; } else { ortho_zoom_change = (float(mouse_down_x) - float(mx)) / float(width); set_projection(); } } //Middle Mouse Button - Panning if (middle_mouse_down){ pan_x_change = (float(mouse_down_x) - float(mx)) / float(width) * 5; pan_y_change = (float(mouse_down_y) - float(my)) / float(height) * 5; } //Force redisplay if (left_mouse_down || middle_mouse_down || right_mouse_down){ glutPostRedisplay(); } } /** Enable lighting & materials **/ static void lighting() { glShadeModel(GL_SMOOTH); //glShadeModel(GL_FLAT); //Setup Material GLfloat mat_ambient[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_diffuse[] = {(GLfloat)0.9, (GLfloat)0.9, (GLfloat)0.9, (GLfloat)1.0}; GLfloat mat_specular[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_shininess[] = {(GLfloat)50}; glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); //Setup Light(s) GLfloat light_position[] = {30.0, 30.0, 30.0, 0.0}; GLfloat white_light[] = {1.0, 1.0, 1.0, 1.0}; glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light); glLightfv(GL_LIGHT0, GL_SPECULAR, white_light); //Setup Ambient Light //GLfloat lmodel_ambient[] = {(GLfloat)0.2, (GLfloat)0.2, (GLfloat)0.2, (GLfloat)1.0}; //Turn on lighting glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); } //Load Texture static void load_texture(char* filename) { texture = new MyBitmap(filename); if (!texture->loaded){ cout << "Could not load texture." << endl; exit(0); } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &texName); //Allocate Texture Name glBindTexture(GL_TEXTURE_2D, texName); //Select current texture glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texture->width, texture->height, 0, GL_RGB, GL_UNSIGNED_BYTE, texture->data); glEnable( GL_TEXTURE_2D ); delete texture; } /** Clear out the screen **/ static void init() { //Load model m1abrams = new OBJModel("models/m1abrams.obj"); m1abrams->loadTexture("textures/M1_ABRAM.bmp"); humveehardtop = new OBJModel("models/humveehardtop.obj"); humveehardtop->loadTexture("textures/humveehardtop.bmp"); uhtiger = new OBJModel("models/uhtiger.obj"); uhtiger->loadTexture("textures/uhtiger.bmp"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\quakeplasma.obj"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\uhtiger.obj"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\humveehardtop.obj"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\ussoldier1.obj"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\M1_ABRAM.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\plasma.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\uhtiger.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\humveehardtop.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\ussoldier01.bmp"); glClearColor(0.0, 0.0, 0.0, 0.0); //Set up lighting lighting(); //Anti-Aliasing - /* + glEnable (GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glHint (GL_LINE_SMOOTH_HINT, GL_DONT_CARE); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); + glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glLineWidth (1); - */ + //Backface culling glEnable(GL_CULL_FACE); } /** Main function **/ int main(int argc, char** argv) { cout << "Firing up OBJViewer" << endl; cout << "===================" << endl << endl; cout << "Camera Motion " << endl; cout << "Orbit: Left click and drag mouse" << endl; cout << "Panning: Middle click and drag mouse" << endl; cout << "Dolly: Right click and drag mouse" << endl << endl; cout << "Viewport Controls " << endl; cout << "w: Toggle wireframe" << endl; cout << "s: Toggle shaded mode" << endl; cout << "p: Perspective mode" << endl; cout << "o: Orthographic mode" << endl; cout << "+ or z: Zoom in" << endl; cout << "- or Z(shift-z): Zoom out" << endl; cout << "c: Reset view" << endl << endl; cout << "Deluxe Light Cycle Controls " << endl; cout << "left/right arrow keys: Turn front wheels" << endl; cout << "[ and ]: Open/close canopy" << endl << endl; cout << "Escape: Quit" << endl; glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 100); glutCreateWindow("OBJViewer Test - Leonard Teo"); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard_func); glutSpecialFunc(functionKeys); glutMouseFunc(mouse_clicks); glutMotionFunc(mouse_move); glutMainLoop(); //Cleanup /* delete lightcycle_chassis; delete lightcycle_canopy; delete lightcycle_axel_front_right; delete lightcycle_axel_front_left; delete lightcycle_wheel_front_right; delete lightcycle_wheel_front_left; delete lightcycle_wheel_rear_right; delete lightcycle_wheel_rear_left; */ delete camera; exit(0); } \ No newline at end of file
leonardteo/OBJViewer
7fd7bdf8d7b0971e1b70e5775d6744928a510bf2
Fixed file location
diff --git a/OBJViewer.cpp b/OBJViewer.cpp index c4c9042..bcbeb29 100644 --- a/OBJViewer.cpp +++ b/OBJViewer.cpp @@ -85,609 +85,609 @@ static GLuint texName; Draw a 24x24 grid **/ static void grid(int scale = 1) { //Turn off lighting for grid glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); //Start drawing lines glBegin(GL_LINES); glColor3f(0.5, 0.5, 0.5); for (int x=-12; x<=12; x++){ if (x != 0){ glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(-12*scale)); glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(12*scale)); } } for (int z=-12; z<=12; z++){ if (z != 0){ glVertex3f((GLfloat)(-12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); glVertex3f((GLfloat)(12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); } } glEnd(); //Make sure the lines at the origin are nice and different glBegin(GL_LINES); glColor3f(0.75, 0.75, 0.75); glVertex3f(0, 0, (GLfloat)(-12*scale)); glVertex3f(0, 0, (GLfloat)(12*scale)); glVertex3f((GLfloat)(-12*scale), 0, 0); glVertex3f((GLfloat)(12*scale), 0, 0); glEnd(); glFlush(); //Turn lighting back on glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); } static void draw_models() { //Draw all three models (let's be awesome) glPushMatrix(); glTranslatef(-15, 0, 0); m1abrams->draw(); glPopMatrix(); uhtiger->draw(); glPushMatrix(); glTranslatef(15,0,0); humveehardtop->draw(); glPopMatrix(); //Switch model /* switch (model) { case 0: m1abrams->draw(); break; case 1: humveehardtop->draw(); break; case 2: uhtiger->draw(); break; } */ } /** Display function **/ static void display() { //Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); /** Camera setup **/ //Translate & Rotate Polar Views glTranslatef(-(GLfloat)(camera->point_of_interest->x + pan_x_change), (GLfloat)(camera->point_of_interest->y + pan_y_change), -((GLfloat)camera->distance + (GLfloat)cam_distance_change)); //Translate along the z axis away from camera glRotatef((GLfloat)camera->twist + (GLfloat)twist_change, (GLfloat)0.0, (GLfloat)0.0, (GLfloat)1.0); //Rotate around z axis (usually by 0) glRotatef((GLfloat)camera->elevation + (GLfloat)elevation_change, (GLfloat)1.0, (GLfloat)0.0, (GLfloat)0.0); //Rotate around x axis glRotatef((GLfloat)camera->azimuth + (GLfloat)azimuth_change, (GLfloat)0.0, (GLfloat)1.0, (GLfloat)0.0); //Rotate around y axis //Draw grid grid(); //Wireframe switching //If shaded mode, draw the model with shading, else only draw the wireframe if (shaded_mode){ //Setup polygon offset for drawing wire on shaded glPolygonOffset(1.0, 1.0); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glColor3f(1.0, 1.0, 1.0); //Draw the obj model draw_models(); glDisable(GL_POLYGON_OFFSET_FILL); //If show wireframe, render the wireframe on top of shaded object if (show_wireframe){ glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glColor3f(0.0, 0.0, 0.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); } } else { //Wireframe only glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); glDisable(GL_CULL_FACE); glColor3f(1.0, 1.0, 1.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE); } glutSwapBuffers(); } /** Sets the projection **/ static void set_projection() { glViewport(0, 0, (GLsizei) width, (GLsizei) height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Perspective mode or ortho float aspect_ratio = (float)width / (float)height; if (camera->perspective_mode){ gluPerspective(camera->fov, GLfloat(aspect_ratio), camera->near_plane, camera->far_plane); } else { //Keep aspect ratio float left, right, bottom, top, temp_ortho_zoom; temp_ortho_zoom = camera->ortho_zoom + ortho_zoom_change; if (aspect_ratio < 1.0){ left = -temp_ortho_zoom; right = temp_ortho_zoom; bottom = -temp_ortho_zoom * ( 1.0f / aspect_ratio ); top = temp_ortho_zoom * ( 1.0f / aspect_ratio ); } else { left = -temp_ortho_zoom * aspect_ratio; right = temp_ortho_zoom * aspect_ratio; bottom = -temp_ortho_zoom; top = temp_ortho_zoom; } glOrtho(left, right, bottom, top, -camera->far_plane, camera->far_plane); } } /** Reshape function **/ static void reshape(int new_width, int new_height) { //Set Global Variables width = new_width; height = new_height; set_projection(); } /** Keyboard Input **/ static void keyboard_func(unsigned char key, int mx, int my) { switch (key) { //Camera Motion for Assignment case 'u': camera->point_of_interest->y -= 0.02f; glutPostRedisplay(); break; case 'd': camera->point_of_interest->y += 0.02f; glutPostRedisplay(); break; case 'l': camera->point_of_interest->x -= 0.02f; glutPostRedisplay(); break; case 'r': camera->point_of_interest->x += 0.02f; glutPostRedisplay(); break; case 'f': camera->distance -= 0.2f; glutPostRedisplay(); break; case 'b': camera->distance += 0.2f; glutPostRedisplay(); break; //Views case 'c': //Reset views //Destroy and reinitialize camera delete camera; camera = new PolarCamera(); set_projection(); break; case 'w': //Show Wireframe show_wireframe = show_wireframe == false ? true : false; break; case 's': //Shaded Model shaded_mode = shaded_mode == false ? true : false; break; case 'p': //Perspective camera->perspective_mode = true; set_projection(); break; case 'o': //Ortho camera->perspective_mode = false; set_projection(); break; case 'z': //Zoom forward if (camera->perspective_mode){ camera->fov -= 1.5f; } else { camera->ortho_zoom -= 0.1f; } set_projection(); break; case 'Z': //Zoom back if (camera->perspective_mode){ camera->fov += 1.5f; } else { camera->ortho_zoom += 0.1f; } set_projection(); break; //Alternative zoom case '+': //Zoom forward if (camera->perspective_mode){ camera->fov -= 1.5f; } else { camera->ortho_zoom -= 0.1f; } set_projection(); break; case '-': //Zoom back if (camera->perspective_mode){ camera->fov += 1.5f; } else { camera->ortho_zoom += 0.1f; } set_projection(); break; //Models case '1': model = 0; break; case '2': model = 1; break; case '3': model = 2; break; case '4': model = 3; break; case '5': model = 4; break; case '6': model = 5; break; case '7': model = 6; break; case '8': model = 7; break; //Exit case 27: exit(0); } glutPostRedisplay(); } /** Function Keys **/ static void functionKeys(int key, int mx, int my) { } /** Mouse Clicks **/ static void mouse_clicks(int button, int state, int mx, int my) { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) { left_mouse_down = true; //Set mouse down state to true mouse_down_x = mx; //Record screen position of mouse when user clicked left button mouse_down_y = my; //cout << "Left mouse button clicked at:" << mx << ", " << my << endl; } else { left_mouse_down = false; //Add changes to camera camera->azimuth += azimuth_change; camera->elevation += elevation_change; //Reset deltas azimuth_change = 0; elevation_change = 0; } break; case GLUT_RIGHT_BUTTON: //Move camera forward and back if (state == GLUT_DOWN) { right_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { right_mouse_down = false; //Reset distance deltas camera->distance += cam_distance_change; cam_distance_change = 0; //Ortho camera->ortho_zoom += ortho_zoom_change; ortho_zoom_change = 0; } break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_DOWN) { middle_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { middle_mouse_down = false; //Reset panning deltas camera->point_of_interest->x += pan_x_change; camera->point_of_interest->y += pan_y_change; pan_x_change = 0; pan_y_change = 0; } break; } } /** Mouse Movement **/ static void mouse_move(int mx, int my) { //Only bother processing if mouse button is pressed //Left Mouse Button - Orbit if (left_mouse_down){ azimuth_change = - (float(mouse_down_x) - float(mx)) / float(width) * 90; elevation_change = - (float(mouse_down_y) - float(my)) / float(height) * 90; } //Right Mouse Button - Dolly if (right_mouse_down){ if (camera->perspective_mode){ cam_distance_change = (float(mouse_down_x) - float(mx)) / float(width) * 10; } else { ortho_zoom_change = (float(mouse_down_x) - float(mx)) / float(width); set_projection(); } } //Middle Mouse Button - Panning if (middle_mouse_down){ pan_x_change = (float(mouse_down_x) - float(mx)) / float(width) * 5; pan_y_change = (float(mouse_down_y) - float(my)) / float(height) * 5; } //Force redisplay if (left_mouse_down || middle_mouse_down || right_mouse_down){ glutPostRedisplay(); } } /** Enable lighting & materials **/ static void lighting() { glShadeModel(GL_SMOOTH); //glShadeModel(GL_FLAT); //Setup Material GLfloat mat_ambient[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_diffuse[] = {(GLfloat)0.9, (GLfloat)0.9, (GLfloat)0.9, (GLfloat)1.0}; GLfloat mat_specular[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_shininess[] = {(GLfloat)50}; glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); //Setup Light(s) GLfloat light_position[] = {30.0, 30.0, 30.0, 0.0}; GLfloat white_light[] = {1.0, 1.0, 1.0, 1.0}; glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light); glLightfv(GL_LIGHT0, GL_SPECULAR, white_light); //Setup Ambient Light //GLfloat lmodel_ambient[] = {(GLfloat)0.2, (GLfloat)0.2, (GLfloat)0.2, (GLfloat)1.0}; //Turn on lighting glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); } //Load Texture static void load_texture(char* filename) { texture = new MyBitmap(filename); if (!texture->loaded){ cout << "Could not load texture." << endl; exit(0); } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &texName); //Allocate Texture Name glBindTexture(GL_TEXTURE_2D, texName); //Select current texture glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texture->width, texture->height, 0, GL_RGB, GL_UNSIGNED_BYTE, texture->data); glEnable( GL_TEXTURE_2D ); delete texture; } /** Clear out the screen **/ static void init() { //Load model m1abrams = new OBJModel("models/m1abrams.obj"); m1abrams->loadTexture("textures/M1_ABRAM.bmp"); humveehardtop = new OBJModel("models/humveehardtop.obj"); humveehardtop->loadTexture("textures/humveehardtop.bmp"); - uhtiger = new OBJModel("/Users/leonardteo/Documents/UniProjects/OBJViewer/models/uhtiger.obj"); - uhtiger->loadTexture("/Users/leonardteo/Documents/UniProjects/OBJViewer/textures/uhtiger.bmp"); + uhtiger = new OBJModel("models/uhtiger.obj"); + uhtiger->loadTexture("textures/uhtiger.bmp"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\quakeplasma.obj"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\uhtiger.obj"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\humveehardtop.obj"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\ussoldier1.obj"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\M1_ABRAM.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\plasma.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\uhtiger.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\humveehardtop.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\ussoldier01.bmp"); glClearColor(0.0, 0.0, 0.0, 0.0); //Set up lighting lighting(); //Anti-Aliasing /* glEnable (GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint (GL_LINE_SMOOTH_HINT, GL_DONT_CARE); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glLineWidth (1); */ //Backface culling glEnable(GL_CULL_FACE); } /** Main function **/ int main(int argc, char** argv) { cout << "Firing up OBJViewer" << endl; cout << "===================" << endl << endl; cout << "Camera Motion " << endl; cout << "Orbit: Left click and drag mouse" << endl; cout << "Panning: Middle click and drag mouse" << endl; cout << "Dolly: Right click and drag mouse" << endl << endl; cout << "Viewport Controls " << endl; cout << "w: Toggle wireframe" << endl; cout << "s: Toggle shaded mode" << endl; cout << "p: Perspective mode" << endl; cout << "o: Orthographic mode" << endl; cout << "+ or z: Zoom in" << endl; cout << "- or Z(shift-z): Zoom out" << endl; cout << "c: Reset view" << endl << endl; cout << "Deluxe Light Cycle Controls " << endl; cout << "left/right arrow keys: Turn front wheels" << endl; cout << "[ and ]: Open/close canopy" << endl << endl; cout << "Escape: Quit" << endl; glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 100); glutCreateWindow("OBJViewer Test - Leonard Teo"); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard_func); glutSpecialFunc(functionKeys); glutMouseFunc(mouse_clicks); glutMotionFunc(mouse_move); glutMainLoop(); //Cleanup /* delete lightcycle_chassis; delete lightcycle_canopy; delete lightcycle_axel_front_right; delete lightcycle_axel_front_left; delete lightcycle_wheel_front_right; delete lightcycle_wheel_front_left; delete lightcycle_wheel_rear_right; delete lightcycle_wheel_rear_left; */ delete camera; exit(0); } \ No newline at end of file
leonardteo/OBJViewer
b4f1178d781dc043603b5790eb342753a8a48f76
Compiles on OSX
diff --git a/MyBitmap.cpp b/MyBitmap.cpp index 2e4beb2..60cbd64 100644 --- a/MyBitmap.cpp +++ b/MyBitmap.cpp @@ -1,265 +1,265 @@ //File: Bitmap.cpp //Written by: Mark Bernard //on GameDev.net: Captain Jester //e-mail: [email protected] //Please feel free to use and abuse this code as much //as you like. But, please give me some credit for //starting you off on the right track. // //The file Bitmap.h goes along with this file // #include "MyBitmap.h" //basic constructor MyBitmap::MyBitmap(){ reset(); } //constructor loads the bitmap when it is created -MyBitmap::MyBitmap(char *file){ +MyBitmap::MyBitmap(const char *file){ reset(); loadBMP(file); } //destructor MyBitmap::~MyBitmap(){ if(colours!=0) { delete[] colours; } if(data!=0) { delete[] data; } } //load a bitmap from a file and represent it correctly //in memory -bool MyBitmap::loadBMP(char *file) { +bool MyBitmap::loadBMP(const char *file) { FILE *in; //file stream for reading - char *tempData; //temp storage for image data + char *tempData; //temp storage for image data int numColours; //total available colours //bitmap is not loaded yet loaded=false; //make sure memory is not lost if(colours!=0) { delete[] colours; } if(data!=0) { delete[] data; } //open the file for reading in binary mode in=fopen(file,"rb"); //if the file does not exist return in error if(in==NULL) { error="File not found"; fclose(in); return false; } //read in the entire BITMAPFILEHEADER fread(&bmfh,sizeof(BitmapFileHeader),1,in); cout << "sizeof(BitmapFileHeader)=" << sizeof(BitmapFileHeader) << endl; //check for the magic number that says this is a bitmap if(bmfh.bfType!=BITMAP_MAGIC_NUMBER) { error="File is not in DIB format"; fclose(in); return false; } //read in the entire BITMAPINFOHEADER fread(&bmih,sizeof(BitmapInfoHeader),1,in); cout << "sizeof(BitmapInfoHeader)=" << sizeof(BitmapInfoHeader) << endl; //save the width, height and bits per pixel for external use width=bmih.biWidth; height=bmih.biHeight; bpp=bmih.biBitCount; cout << "biBitCount =" << bmih.biBitCount << endl; cout << "biClrImportant =" << bmih.biClrImportant << endl; cout << "biClrUsed =" << bmih.biClrUsed << endl; cout << "biCompression =" << bmih.biCompression << endl; cout << "biHeight =" << bmih.biHeight << endl; cout << "biPlanes =" << bmih.biPlanes << endl; cout << "biSize =" << bmih.biSize << endl; cout << "biSizeImage =" << bmih.biSizeImage << endl; cout << "biWidth =" << bmih.biWidth << endl; cout << "biXPelsPerMeter =" << bmih.biXPelsPerMeter << endl; cout << "biYPelsPerMeter =" << bmih.biYPelsPerMeter << endl; //calculate the size of the image data with padding dataSize=(width*height*(unsigned int)(bmih.biBitCount/8.0)); //calculate the number of available colours numColours=1<<bmih.biBitCount; //if the bitmap is not 8 bits per pixel or more //return in error if(bpp<8) { error="File is not 8 or 24 bits per pixel"; fclose(in); return false; } //load the palette for 8 bits per pixel if(bpp==8) { colours=new RGBQuad[numColours]; fread(colours,sizeof(RGBQuad),numColours,in); } //set up the temporary buffer for the image data tempData=new char[dataSize]; //exit if there is not enough memory if(tempData==NULL) { error="Not enough memory to allocate a temporary buffer"; fclose(in); return false; } //read in the entire image fread(tempData,sizeof(char),dataSize,in); //close the file now that we have all the info fclose(in); //calculate the witdh of the final image in bytes byteWidth=padWidth=(int)((float)width*(float)bpp/8.0); //adjust the width for padding as necessary while(padWidth%4!=0) { padWidth++; } //change format from GBR to RGB if(bpp==8) { loaded=convert8(tempData); } else if(bpp==24) { loaded=convert24(tempData); } //clean up memory delete[] tempData; //bitmap is now loaded error="Bitmap loaded"; //return success return loaded; } //function to set the inital values void MyBitmap::reset(void) { loaded=false; colours=0; data=0; error=""; } bool MyBitmap::convert24(char* tempData) { int offset,diff; diff=width*height*RGB_BYTE_SIZE; //allocate the buffer for the final image data data=new char[diff]; //exit if there is not enough memory if(data==NULL) { error="Not enough memory to allocate an image buffer"; delete[] data; return false; } if(height>0) { offset=padWidth-byteWidth; //count backwards so you start at the front of the image for(int i=0;i<dataSize;i+=3) { //jump over the padding at the start of a new line if((i+1)%padWidth==0) { i+=offset; } //transfer the data *(data+i+2)=*(tempData+i); *(data+i+1)=*(tempData+i+1); *(data+i)=*(tempData+i+2); } } //image parser for a forward image else { offset=padWidth-byteWidth; int j=dataSize-3; //count backwards so you start at the front of the image //here you can start from the back of the file or the front, //after the header The only problem is that some programs //will pad not only the data, but also the file size to //be divisible by 4 bytes. for(int i=0;i<dataSize;i+=3) { //jump over the padding at the start of a new line if((i+1)%padWidth==0) { i+=offset; } //transfer the data *(data+j+2)=*(tempData+i); *(data+j+1)=*(tempData+i+1); *(data+j)=*(tempData+i+2); j-=3; } } return true; } bool MyBitmap::convert8(char* tempData) { int offset,diff; diff=width*height*RGB_BYTE_SIZE; //allocate the buffer for the final image data data=new char[diff]; //exit if there is not enough memory if(data==NULL) { error="Not enough memory to allocate an image buffer"; delete[] data; return false; } if(height>0) { offset=padWidth-byteWidth; int j=0; //count backwards so you start at the front of the image for(int i=0;i<dataSize*RGB_BYTE_SIZE;i+=3) { //jump over the padding at the start of a new line if((i+1)%padWidth==0) { i+=offset; } //transfer the data *(data+i)=colours[*(tempData+j)].rgbRed; *(data+i+1)=colours[*(tempData+j)].rgbGreen; *(data+i+2)=colours[*(tempData+j)].rgbBlue; j++; } } //image parser for a forward image else { offset=padWidth-byteWidth; int j=dataSize-1; //count backwards so you start at the front of the image for(int i=0;i<dataSize*RGB_BYTE_SIZE;i+=3) { //jump over the padding at the start of a new line if((i+1)%padWidth==0) { i+=offset; } //transfer the data *(data+i)=colours[*(tempData+j)].rgbRed; *(data+i+1)=colours[*(tempData+j)].rgbGreen; *(data+i+2)=colours[*(tempData+j)].rgbBlue; j--; } } return true; } diff --git a/MyBitmap.h b/MyBitmap.h index 0a031a8..e638008 100644 --- a/MyBitmap.h +++ b/MyBitmap.h @@ -1,85 +1,85 @@ #ifndef _BITMAP_H #define _BITMAP_H //File: Bitmap.h //Written by: Mark Bernard //on GameDev.net: Captain Jester //e-mail: [email protected] //Please feel free to use and abuse this code as much //as you like. But, please give me some credit for //starting you off on the right track. // //The file Bitmap.cpp goes along with this file // #include <iostream> #include <cstdio> #include <string> using namespace std; const short BITMAP_MAGIC_NUMBER=19778; const int RGB_BYTE_SIZE=3; #pragma pack(push,bitmap_data,1) typedef struct tagRGBQuad { char rgbBlue; char rgbGreen; char rgbRed; char rgbReserved; } RGBQuad; typedef struct tagBitmapFileHeader { unsigned short bfType; unsigned int bfSize; unsigned short bfReserved1; unsigned short bfReserved2; unsigned int bfOffBits; } BitmapFileHeader; typedef struct tagBitmapInfoHeader { unsigned int biSize; int biWidth; int biHeight; unsigned short biPlanes; unsigned short biBitCount; unsigned int biCompression; unsigned int biSizeImage; int biXPelsPerMeter; int biYPelsPerMeter; unsigned int biClrUsed; unsigned int biClrImportant; } BitmapInfoHeader; #pragma pack(pop,bitmap_data) class MyBitmap { public: //variables RGBQuad *colours; char *data; bool loaded; int width,height; unsigned short bpp; string error; //methods MyBitmap(void); - MyBitmap(char *); + MyBitmap(const char *); ~MyBitmap(); - bool loadBMP(char *); + bool loadBMP(const char *); private: //variables BitmapFileHeader bmfh; BitmapInfoHeader bmih; int byteWidth; //the width in bytes of the image int padWidth; //the width in bytes of the added image unsigned int dataSize; //size of the data in the file //methods void reset(void); bool convert24(char *); //convert to 24bit RGB bottom up data bool convert8(char *); //convert to 24bit RGB bottom up data }; #endif //_BITMAP_H diff --git a/OBJModel.cpp b/OBJModel.cpp index bc0122a..7a7d076 100644 --- a/OBJModel.cpp +++ b/OBJModel.cpp @@ -1,305 +1,305 @@ #include "OBJModel.h" using namespace std; //Constructor -OBJModel::OBJModel(char* fileName) +OBJModel::OBJModel(const char* fileName) { this->init(); this->load(fileName); } //Free memory OBJModel::~OBJModel(void) { delete this->vertices; delete this->normals; delete this->uvs; delete this->index; delete this->normalsIndex; delete this->uvIndex; } //General class initialization void OBJModel::init() { this->numVertices = 0; this->numFaces = 0; this->numUVs = 0; this->numNormals = 0; this->vertices = NULL; this->uvs = NULL; this->index = NULL; this->normals = NULL; this->uvIndex = NULL; } -void OBJModel::load(char* fileName) +void OBJModel::load(const char* fileName) { char buffer[255]; //Open file for reading ifstream file; file.open(fileName); if (!file.is_open()) { //If file isn't open cout << "Error loading file: " << fileName << endl; return; } else { //First pass of reading the file counts the data while ( !file.eof() ){ //Read the line file.getline(buffer, 255); //Read the line switch(buffer[0]) { //Vertex case 'v': switch(buffer[1]) { case ' ': this->numVertices++; break; case 'n': this->numNormals++; break; case 't': this->numUVs++; break; } break; //Face case 'f': this->numFaces++; break; default: break; } } //end of file //Echo the stats printf("fileName: %s \n", fileName); printf("Vertices: %d \n", this->numVertices); printf("Vertex Normals: %d \n", this->numNormals); printf("Faces: %d \n", this->numFaces); printf("\n"); //Allocate memory for data //Init vertices this->vertices = new Vector3*[this->numVertices]; this->index = new int*[this->numFaces]; //Triangles now //Init normals this->normals = new Vector3*[this->numNormals]; this->normalsIndex = new int*[this->numFaces]; //Triangles //Init UV's this->uvs = new UV*[this->numUVs]; this->uvIndex = new int*[this->numFaces]; //Initialize each of the indices for (int i=0; i<this->numFaces; i++){ this->index[i] = new int[3]; this->normalsIndex[i] = new int[3]; this->uvIndex[i] = new int[3]; for (int j=0; j<3; j++){ this->index[i][j] = 0; this->normalsIndex[i][j] = 0; this->uvIndex[i][j] = 0; } } //Second pass of file to load data file.clear(); //Clear eof status file.seekg(0, ios::beg); //Move cursor to beginning int currentVertex = 0; int currentIndex = 0; int currentNormal = 0; int currentUV = 0; int currentUVIndex = 0; int currentNormalIndex = 0; while (!file.eof()){ //Read line file.getline(buffer, 255); switch (buffer[0]){ //Vertex case 'v': switch(buffer[1]){ case ' ': //Create new vertex this->vertices[currentVertex] = new Vector3(); sscanf(buffer, "v %f %f %f", &this->vertices[currentVertex]->x, &this->vertices[currentVertex]->y, &this->vertices[currentVertex]->z); currentVertex++; break; case 'n': //Create new vertex normal this->normals[currentNormal] = new Vector3(); sscanf(buffer, "vn %f %f %f", &this->normals[currentNormal]->x, &this->normals[currentNormal]->y, &this->normals[currentNormal]->z); currentNormal++; break; case 't': //Create new UV this->uvs[currentUV] = new UV(); sscanf(buffer, "vt %f %f", &this->uvs[currentUV]->u, &this->uvs[currentUV]->v); currentUV++; break; } break; case 'f': //sscanf(buffer, "f %d/%*d/%d %d/%*d/%d %d/%*d/%d", &this->index[currentIndex][0], &this->normalsIndex[currentNormalIndex][0], &this->index[currentIndex][1], &this->normalsIndex[currentNormalIndex][1], &this->index[currentIndex][2], &this->normalsIndex[currentNormalIndex][2]); sscanf(buffer, "f %d/%d/%d %d/%d/%d %d/%d/%d", &this->index[currentIndex][0], &this->uvIndex[currentUVIndex][0], &this->normalsIndex[currentNormalIndex][0], &this->index[currentIndex][1], &this->uvIndex[currentUVIndex][1], &this->normalsIndex[currentNormalIndex][1], &this->index[currentIndex][2], &this->uvIndex[currentUVIndex][2], &this->normalsIndex[currentNormalIndex][2]); currentIndex++; currentNormalIndex++; currentUVIndex++; break; } } //end of file //Release file pointer file.close(); } //Debug - echo out all the vertices and faces /* printf("Vertices: \n"); for(int i=0; i< this->numVertices; i++) { printf(" %f %f %f \n", this->vertices[i]->x, this->vertices[i]->y, this->vertices[i]->z ); } printf("\n\nUV coordinates: \n"); for (int i=0; i< this->numUVs; i++) { printf(" %f %f \n", this->uvs[i]->u, this->uvs[i]->v); } printf("\n\nVertex Normals: \n"); for(int i=0; i< this->numNormals ; i++) { printf(" %f %f %f \n", this->normals[i]->x, this->normals[i]->y, this->normals[i]->z); } printf("\n\nIndex/UV/Normal: \n"); for(int i=0; i< this->numFaces; i++){ printf(" %d/%d/%d %d/%d/%d %d/%d/%d\n", this->index[i][0], this->uvIndex[i][0], this->normalsIndex[i][0], this->index[i][1], this->uvIndex[i][1], this->normalsIndex[i][1], this->index[i][2], this->uvIndex[i][2], this->normalsIndex[i][2]); } */ //decrement all indices to cater for OpenGL (OBJ indices start at 1) for(int i = 0; i < this->numFaces; i++) { for(int j=0; j<3; j++){ this->index[i][j]--; this->normalsIndex[i][j]--; this->uvIndex[i][j]--; } } } /** Drawing routine **/ void OBJModel::draw() { //Load texture glBindTexture(GL_TEXTURE_2D, this->texture); //For each face, draw a quad glBegin(GL_TRIANGLES); for (int face = 0; face < this->numFaces; face++) { //Draw the vertex at each of the vertex numbders glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][0]]->u, (GLfloat)this->uvs[this->uvIndex[face][0]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][0]]->x, (GLfloat)this->normals[this->normalsIndex[face][0]]->y, (GLfloat)this->normals[this->normalsIndex[face][0]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][0]]->x, (GLfloat)this->vertices[this->index[face][0]]->y, (GLfloat)this->vertices[this->index[face][0]]->z); glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][1]]->u, (GLfloat)this->uvs[this->uvIndex[face][1]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][1]]->x, (GLfloat)this->normals[this->normalsIndex[face][1]]->y, (GLfloat)this->normals[this->normalsIndex[face][1]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][1]]->x, (GLfloat)this->vertices[this->index[face][1]]->y, (GLfloat)this->vertices[this->index[face][1]]->z); glTexCoord2f((GLfloat)this->uvs[this->uvIndex[face][2]]->u, (GLfloat)this->uvs[this->uvIndex[face][2]]->v); glNormal3f((GLfloat)this->normals[this->normalsIndex[face][2]]->x, (GLfloat)this->normals[this->normalsIndex[face][2]]->y, (GLfloat)this->normals[this->normalsIndex[face][2]]->z); glVertex3f((GLfloat)this->vertices[this->index[face][2]]->x, (GLfloat)this->vertices[this->index[face][2]]->y, (GLfloat)this->vertices[this->index[face][2]]->z); /* Non-Optimized code for debugging //Get vertex numbers int v1, v2, v3; v1 = this->index[face][0]; v2 = this->index[face][1]; v3 = this->index[face][2]; //Get Normal numbers int n1, n2, n3; n1 = this->normalsIndex[face][0]; n2 = this->normalsIndex[face][1]; n3 = this->normalsIndex[face][2]; //Get UVs int uv1, uv2, uv3; uv1 = this->uvIndex[face][0]; uv2 = this->uvIndex[face][1]; uv3 = this->uvIndex[face][2]; //Draw the vertex at each of the vertex numbders glTexCoord2f((GLfloat)this->uvs[uv1]->u, (GLfloat)this->uvs[uv1]->v); glNormal3f((GLfloat)this->normals[n1]->x, (GLfloat)this->normals[n1]->y, (GLfloat)this->normals[n1]->z); glVertex3f((GLfloat)this->vertices[v1]->x, (GLfloat)this->vertices[v1]->y, (GLfloat)this->vertices[v1]->z); glTexCoord2f((GLfloat)this->uvs[uv2]->u, (GLfloat)this->uvs[uv2]->v); glNormal3f((GLfloat)this->normals[n2]->x, (GLfloat)this->normals[n2]->y, (GLfloat)this->normals[n2]->z); glVertex3f((GLfloat)this->vertices[v2]->x, (GLfloat)this->vertices[v2]->y, (GLfloat)this->vertices[v2]->z); glTexCoord2f((GLfloat)this->uvs[uv3]->u, (GLfloat)this->uvs[uv3]->v); glNormal3f((GLfloat)this->normals[n3]->x, (GLfloat)this->normals[n3]->y, (GLfloat)this->normals[n3]->z); glVertex3f((GLfloat)this->vertices[v3]->x, (GLfloat)this->vertices[v3]->y, (GLfloat)this->vertices[v3]->z); */ } glEnd(); glFlush(); } /*** Load Texture ***/ -void OBJModel::loadTexture(char* fileName) +void OBJModel::loadTexture(const char* fileName) { this->image = new MyBitmap(fileName); if (!image->loaded){ cout << "Could not load texture." << endl; exit(0); } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &this->texture); //Allocate Texture Name glBindTexture(GL_TEXTURE_2D, this->texture); //Select current texture glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->image->width, this->image->height, 0, GL_RGB, GL_UNSIGNED_BYTE, this->image->data); glEnable( GL_TEXTURE_2D ); delete image; } \ No newline at end of file diff --git a/OBJModel.h b/OBJModel.h index 903890a..30a1b73 100644 --- a/OBJModel.h +++ b/OBJModel.h @@ -1,81 +1,89 @@ /** My attempt at an OBJ parser Leonard Teo 25 September 2010 Done: Only supports triangles - remember to triangulate all models To DO: - UV mapping - Generate normals if a model doesn't have them - Handle groups and materials **/ #ifndef OBJMODEL_H #define OBJMODEL_H #include <iostream> #include <fstream> #include <stdio.h> #include <string> -#include <GL\glut.h> + +#ifdef OSX + #include <OpenGL/gl.h> + #include <OpenGL/glu.h> + #include <GLUT/GLUT.h> +#else + #include <GL/glut.h> +#endif + #include "Vector3.h" #include "MyBitmap.h" struct UV { float u; float v; }; class OBJModel { public: //Constructor - OBJModel(char* fileName); + OBJModel(const char* fileName); //Destructor ~OBJModel(void); //Load Texture - void loadTexture(char* fileName); + void loadTexture(const char* fileName); //Draw the polygons using OpenGL calls void draw(); //Generate normals - TO DO void generateNormals(); private: //Private data members //Total number of vertices int numVertices; int numFaces; int numUVs; int numNormals; //Data Vector3** vertices; Vector3** normals; UV** uvs; int** index; //2 dimensional arrays: Note these are pointers so that we can do this: this->normals_index[i][j] int** normalsIndex; int** uvIndex; //Texture map MyBitmap* image; GLuint texture; //Initialize the arrays and variables void init(); //Load a model file - void load(char* fileName); + void load(const char* fileName); }; #endif \ No newline at end of file diff --git a/OBJViewer.cpp b/OBJViewer.cpp index 563b412..c4c9042 100644 --- a/OBJViewer.cpp +++ b/OBJViewer.cpp @@ -1,682 +1,693 @@ /** OBJ Viewer **/ #include <iostream> -#include <GL/glut.h> +#include <string> + +#ifdef OSX + #include <OpenGL/gl.h> + #include <OpenGL/glu.h> + #include <GLUT/GLUT.h> +#else + #include <GL/glut.h> +#endif + + #include "PolarCamera.h" #include "OBJModel.h" #include "MyBitmap.h" + using namespace std; //Default Screen Size const int WIDTH = 640; const int HEIGHT = 480; /** Global Variables **/ //Temporary screen width and height int width = WIDTH; int height = HEIGHT; //Mouse position int mouse_x; int mouse_y; int mouse_down_x; //Mouse position when a user clicks int mouse_down_y; //Mouse clicks states bool left_mouse_down = false; bool middle_mouse_down = false; bool right_mouse_down = false; //Model type int model = 0; //Show Wireframe bool show_wireframe = false; bool shaded_mode = true; //Camera - Polar view PolarCamera* camera = new PolarCamera(); //Temporary variables to facilitate Polar camera float azimuth_change = 0; float twist_change = 0; float elevation_change = 0; float cam_distance_change = 0.0; //Panning temporary variables float pan_x_down = 0; //When the pan button is pushed, record this float pan_y_down = 0; float pan_z_down = 0; float pan_x_change = 0; float pan_y_change = 0; //Orthographic zooming temporary variable float ortho_zoom_change = 0; //OBJ Models //OBJModel* objmodel; //Any objmodel for testing OBJModel* m1abrams; OBJModel* humveehardtop; OBJModel* uhtiger; //Texture MyBitmap* texture; static GLuint texName; /** Draw a 24x24 grid **/ static void grid(int scale = 1) { //Turn off lighting for grid glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); //Start drawing lines glBegin(GL_LINES); glColor3f(0.5, 0.5, 0.5); for (int x=-12; x<=12; x++){ if (x != 0){ glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(-12*scale)); glVertex3f((GLfloat)(x*scale), (GLfloat)0.0, (GLfloat)(12*scale)); } } for (int z=-12; z<=12; z++){ if (z != 0){ glVertex3f((GLfloat)(-12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); glVertex3f((GLfloat)(12*scale), (GLfloat)0.0, (GLfloat)(z*scale)); } } glEnd(); //Make sure the lines at the origin are nice and different glBegin(GL_LINES); glColor3f(0.75, 0.75, 0.75); glVertex3f(0, 0, (GLfloat)(-12*scale)); glVertex3f(0, 0, (GLfloat)(12*scale)); glVertex3f((GLfloat)(-12*scale), 0, 0); glVertex3f((GLfloat)(12*scale), 0, 0); glEnd(); glFlush(); //Turn lighting back on glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); } static void draw_models() { //Draw all three models (let's be awesome) glPushMatrix(); glTranslatef(-15, 0, 0); m1abrams->draw(); glPopMatrix(); uhtiger->draw(); glPushMatrix(); glTranslatef(15,0,0); humveehardtop->draw(); glPopMatrix(); //Switch model /* switch (model) { case 0: m1abrams->draw(); break; case 1: humveehardtop->draw(); break; case 2: uhtiger->draw(); break; } */ } /** Display function **/ static void display() { //Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); /** Camera setup **/ //Translate & Rotate Polar Views glTranslatef(-(GLfloat)(camera->point_of_interest->x + pan_x_change), (GLfloat)(camera->point_of_interest->y + pan_y_change), -((GLfloat)camera->distance + (GLfloat)cam_distance_change)); //Translate along the z axis away from camera glRotatef((GLfloat)camera->twist + (GLfloat)twist_change, (GLfloat)0.0, (GLfloat)0.0, (GLfloat)1.0); //Rotate around z axis (usually by 0) glRotatef((GLfloat)camera->elevation + (GLfloat)elevation_change, (GLfloat)1.0, (GLfloat)0.0, (GLfloat)0.0); //Rotate around x axis glRotatef((GLfloat)camera->azimuth + (GLfloat)azimuth_change, (GLfloat)0.0, (GLfloat)1.0, (GLfloat)0.0); //Rotate around y axis //Draw grid grid(); //Wireframe switching //If shaded mode, draw the model with shading, else only draw the wireframe if (shaded_mode){ //Setup polygon offset for drawing wire on shaded glPolygonOffset(1.0, 1.0); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glColor3f(1.0, 1.0, 1.0); //Draw the obj model draw_models(); glDisable(GL_POLYGON_OFFSET_FILL); //If show wireframe, render the wireframe on top of shaded object if (show_wireframe){ glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glColor3f(0.0, 0.0, 0.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); } } else { //Wireframe only glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_TEXTURE_2D); glDisable(GL_CULL_FACE); glColor3f(1.0, 1.0, 1.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw the obj model draw_models(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE); } glutSwapBuffers(); } /** Sets the projection **/ static void set_projection() { glViewport(0, 0, (GLsizei) width, (GLsizei) height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Perspective mode or ortho float aspect_ratio = (float)width / (float)height; if (camera->perspective_mode){ gluPerspective(camera->fov, GLfloat(aspect_ratio), camera->near_plane, camera->far_plane); } else { //Keep aspect ratio float left, right, bottom, top, temp_ortho_zoom; temp_ortho_zoom = camera->ortho_zoom + ortho_zoom_change; if (aspect_ratio < 1.0){ left = -temp_ortho_zoom; right = temp_ortho_zoom; bottom = -temp_ortho_zoom * ( 1.0f / aspect_ratio ); top = temp_ortho_zoom * ( 1.0f / aspect_ratio ); } else { left = -temp_ortho_zoom * aspect_ratio; right = temp_ortho_zoom * aspect_ratio; bottom = -temp_ortho_zoom; top = temp_ortho_zoom; } glOrtho(left, right, bottom, top, -camera->far_plane, camera->far_plane); } } /** Reshape function **/ static void reshape(int new_width, int new_height) { //Set Global Variables width = new_width; height = new_height; set_projection(); } /** Keyboard Input **/ static void keyboard_func(unsigned char key, int mx, int my) { switch (key) { //Camera Motion for Assignment case 'u': camera->point_of_interest->y -= 0.02f; glutPostRedisplay(); break; case 'd': camera->point_of_interest->y += 0.02f; glutPostRedisplay(); break; case 'l': camera->point_of_interest->x -= 0.02f; glutPostRedisplay(); break; case 'r': camera->point_of_interest->x += 0.02f; glutPostRedisplay(); break; case 'f': camera->distance -= 0.2f; glutPostRedisplay(); break; case 'b': camera->distance += 0.2f; glutPostRedisplay(); break; //Views case 'c': //Reset views //Destroy and reinitialize camera delete camera; camera = new PolarCamera(); set_projection(); break; case 'w': //Show Wireframe show_wireframe = show_wireframe == false ? true : false; break; case 's': //Shaded Model shaded_mode = shaded_mode == false ? true : false; break; case 'p': //Perspective camera->perspective_mode = true; set_projection(); break; case 'o': //Ortho camera->perspective_mode = false; set_projection(); break; case 'z': //Zoom forward if (camera->perspective_mode){ camera->fov -= 1.5f; } else { camera->ortho_zoom -= 0.1f; } set_projection(); break; case 'Z': //Zoom back if (camera->perspective_mode){ camera->fov += 1.5f; } else { camera->ortho_zoom += 0.1f; } set_projection(); break; //Alternative zoom case '+': //Zoom forward if (camera->perspective_mode){ camera->fov -= 1.5f; } else { camera->ortho_zoom -= 0.1f; } set_projection(); break; case '-': //Zoom back if (camera->perspective_mode){ camera->fov += 1.5f; } else { camera->ortho_zoom += 0.1f; } set_projection(); break; //Models case '1': model = 0; break; case '2': model = 1; break; case '3': model = 2; break; case '4': model = 3; break; case '5': model = 4; break; case '6': model = 5; break; case '7': model = 6; break; case '8': model = 7; break; //Exit case 27: exit(0); } glutPostRedisplay(); } /** Function Keys **/ static void functionKeys(int key, int mx, int my) { } /** Mouse Clicks **/ static void mouse_clicks(int button, int state, int mx, int my) { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) { left_mouse_down = true; //Set mouse down state to true mouse_down_x = mx; //Record screen position of mouse when user clicked left button mouse_down_y = my; //cout << "Left mouse button clicked at:" << mx << ", " << my << endl; } else { left_mouse_down = false; //Add changes to camera camera->azimuth += azimuth_change; camera->elevation += elevation_change; //Reset deltas azimuth_change = 0; elevation_change = 0; } break; case GLUT_RIGHT_BUTTON: //Move camera forward and back if (state == GLUT_DOWN) { right_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { right_mouse_down = false; //Reset distance deltas camera->distance += cam_distance_change; cam_distance_change = 0; //Ortho camera->ortho_zoom += ortho_zoom_change; ortho_zoom_change = 0; } break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_DOWN) { middle_mouse_down = true; mouse_down_x = mx; mouse_down_y = my; } else { middle_mouse_down = false; //Reset panning deltas camera->point_of_interest->x += pan_x_change; camera->point_of_interest->y += pan_y_change; pan_x_change = 0; pan_y_change = 0; } break; } } /** Mouse Movement **/ static void mouse_move(int mx, int my) { //Only bother processing if mouse button is pressed //Left Mouse Button - Orbit if (left_mouse_down){ azimuth_change = - (float(mouse_down_x) - float(mx)) / float(width) * 90; elevation_change = - (float(mouse_down_y) - float(my)) / float(height) * 90; } //Right Mouse Button - Dolly if (right_mouse_down){ if (camera->perspective_mode){ cam_distance_change = (float(mouse_down_x) - float(mx)) / float(width) * 10; } else { ortho_zoom_change = (float(mouse_down_x) - float(mx)) / float(width); set_projection(); } } //Middle Mouse Button - Panning if (middle_mouse_down){ pan_x_change = (float(mouse_down_x) - float(mx)) / float(width) * 5; pan_y_change = (float(mouse_down_y) - float(my)) / float(height) * 5; } //Force redisplay if (left_mouse_down || middle_mouse_down || right_mouse_down){ glutPostRedisplay(); } } /** Enable lighting & materials **/ static void lighting() { glShadeModel(GL_SMOOTH); //glShadeModel(GL_FLAT); //Setup Material GLfloat mat_ambient[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_diffuse[] = {(GLfloat)0.9, (GLfloat)0.9, (GLfloat)0.9, (GLfloat)1.0}; GLfloat mat_specular[] = {(GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0, (GLfloat)1.0}; GLfloat mat_shininess[] = {(GLfloat)50}; glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); //Setup Light(s) GLfloat light_position[] = {30.0, 30.0, 30.0, 0.0}; GLfloat white_light[] = {1.0, 1.0, 1.0, 1.0}; glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light); glLightfv(GL_LIGHT0, GL_SPECULAR, white_light); //Setup Ambient Light - GLfloat lmodel_ambient[] = {(GLfloat)0.2, (GLfloat)0.2, (GLfloat)0.2, (GLfloat)1.0}; + //GLfloat lmodel_ambient[] = {(GLfloat)0.2, (GLfloat)0.2, (GLfloat)0.2, (GLfloat)1.0}; //Turn on lighting glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); } //Load Texture static void load_texture(char* filename) { texture = new MyBitmap(filename); if (!texture->loaded){ cout << "Could not load texture." << endl; exit(0); } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &texName); //Allocate Texture Name glBindTexture(GL_TEXTURE_2D, texName); //Select current texture glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texture->width, texture->height, 0, GL_RGB, GL_UNSIGNED_BYTE, texture->data); glEnable( GL_TEXTURE_2D ); delete texture; } /** Clear out the screen **/ static void init() { //Load model - m1abrams = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\m1abrams.obj"); - m1abrams->loadTexture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\M1_ABRAM.bmp"); + m1abrams = new OBJModel("models/m1abrams.obj"); + m1abrams->loadTexture("textures/M1_ABRAM.bmp"); - humveehardtop = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\humveehardtop.obj"); - humveehardtop->loadTexture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\humveehardtop.bmp"); + humveehardtop = new OBJModel("models/humveehardtop.obj"); + humveehardtop->loadTexture("textures/humveehardtop.bmp"); - uhtiger = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\uhtiger.obj"); - uhtiger->loadTexture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\uhtiger.bmp"); + uhtiger = new OBJModel("/Users/leonardteo/Documents/UniProjects/OBJViewer/models/uhtiger.obj"); + uhtiger->loadTexture("/Users/leonardteo/Documents/UniProjects/OBJViewer/textures/uhtiger.bmp"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\quakeplasma.obj"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\uhtiger.obj"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\humveehardtop.obj"); //objmodel = new OBJModel("C:\\mayaprojects\\GameEngineTests\\scenes\\ussoldier1.obj"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\M1_ABRAM.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\plasma.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\uhtiger.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\humveehardtop.bmp"); //load_texture("C:\\mayaprojects\\GameEngineTests\\sourceimages\\ussoldier01.bmp"); glClearColor(0.0, 0.0, 0.0, 0.0); //Set up lighting lighting(); //Anti-Aliasing /* glEnable (GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint (GL_LINE_SMOOTH_HINT, GL_DONT_CARE); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glLineWidth (1); */ //Backface culling glEnable(GL_CULL_FACE); } /** Main function **/ int main(int argc, char** argv) { cout << "Firing up OBJViewer" << endl; cout << "===================" << endl << endl; cout << "Camera Motion " << endl; cout << "Orbit: Left click and drag mouse" << endl; cout << "Panning: Middle click and drag mouse" << endl; cout << "Dolly: Right click and drag mouse" << endl << endl; cout << "Viewport Controls " << endl; cout << "w: Toggle wireframe" << endl; cout << "s: Toggle shaded mode" << endl; cout << "p: Perspective mode" << endl; cout << "o: Orthographic mode" << endl; cout << "+ or z: Zoom in" << endl; cout << "- or Z(shift-z): Zoom out" << endl; cout << "c: Reset view" << endl << endl; cout << "Deluxe Light Cycle Controls " << endl; cout << "left/right arrow keys: Turn front wheels" << endl; cout << "[ and ]: Open/close canopy" << endl << endl; cout << "Escape: Quit" << endl; glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 100); glutCreateWindow("OBJViewer Test - Leonard Teo"); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard_func); glutSpecialFunc(functionKeys); glutMouseFunc(mouse_clicks); glutMotionFunc(mouse_move); glutMainLoop(); //Cleanup /* delete lightcycle_chassis; delete lightcycle_canopy; delete lightcycle_axel_front_right; delete lightcycle_axel_front_left; delete lightcycle_wheel_front_right; delete lightcycle_wheel_front_left; delete lightcycle_wheel_rear_right; delete lightcycle_wheel_rear_left; */ delete camera; exit(0); } \ No newline at end of file diff --git a/PolyMesh.cpp b/PolyMesh.cpp deleted file mode 100644 index 57eab00..0000000 --- a/PolyMesh.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include "PolyMesh.h" -#include <iostream> - -using namespace std; - -PolyMesh::PolyMesh(void) -{ - this->init(); -} - -void PolyMesh::init() -{ - this->num_vertices = 0; - this->num_faces = 0; - this->num_normals = 0; - this->vertices = NULL; - this->index = NULL; - this->normals = NULL; -} - -PolyMesh::~PolyMesh(void) -{ -} diff --git a/PolyMesh.h b/PolyMesh.h deleted file mode 100644 index a8b91da..0000000 --- a/PolyMesh.h +++ /dev/null @@ -1,34 +0,0 @@ -/************************* -Polygon Mesh data structure -TO IMPLEMENT -***************************/ - -#ifndef POLYMESH -#define POLYMESH - -class PolyMesh -{ -public: - PolyMesh(void); - ~PolyMesh(void); - - //Total number of vertices - int num_vertices; - int num_faces; - int num_uvs; - int num_normals; - - //Arrays of data - float* faces; - float* vertices; - float* normals; - int* index; - int* normals_index; - float* uvs; - -private: - void init(); - -}; - -#endif \ No newline at end of file diff --git a/UvCoordinates.cpp b/UvCoordinates.cpp deleted file mode 100644 index 7237b7a..0000000 --- a/UvCoordinates.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "UvCoordinates.h" - - -UvCoordinates::UvCoordinates(float u, float v) -{ - this->u = u; - this->v = v; -} - -UvCoordinates::UvCoordinates() -{ - this->u = 0; - this->v = 0; -} - - -UvCoordinates::~UvCoordinates(void) -{ -} diff --git a/UvCoordinates.h b/UvCoordinates.h deleted file mode 100644 index 7550952..0000000 --- a/UvCoordinates.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once -class UvCoordinates -{ -public: - UvCoordinates(float u, float v); - UvCoordinates(); - ~UvCoordinates(void); - - float u; - float v; -}; -
icsharpcode/SharpDevelop-Vendor
7b667a5c5dbd4f0c6fa2b950b2ce541d85a36138
Add SHFB that is currently used for AvalonEdit (newer version won't work)
diff --git a/SHFB/SHFBGuidedInstaller_2014.5.31.0.zip b/SHFB/SHFBGuidedInstaller_2014.5.31.0.zip new file mode 100644 index 0000000..a98b352 Binary files /dev/null and b/SHFB/SHFBGuidedInstaller_2014.5.31.0.zip differ
icsharpcode/SharpDevelop-Vendor
3be5356a0fe5d343a9f965792d702a6ee6b308c8
Upload AvalonDock 1.2.2702 to vendor branch.
diff --git a/AvalonDock/AvalonDock/DockableFloatingWindow.cs b/AvalonDock/AvalonDock/DockableFloatingWindow.cs index f1374d1..dc6663b 100644 --- a/AvalonDock/AvalonDock/DockableFloatingWindow.cs +++ b/AvalonDock/AvalonDock/DockableFloatingWindow.cs @@ -1,278 +1,279 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.ComponentModel; using System.Windows.Markup; using System.Diagnostics; using System.Windows.Threading; using System.Windows.Media.Animation; using System.Windows.Interop; namespace AvalonDock { public class DockableFloatingWindow : FloatingWindow { static DockableFloatingWindow() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml DefaultStyleKeyProperty.OverrideMetadata(typeof(DockableFloatingWindow), new FrameworkPropertyMetadata(typeof(DockableFloatingWindow))); } public DockableFloatingWindow(DockingManager manager) : base(manager) { } Pane _previousPane = null; int _arrayIndexPreviousPane = -1; public DockableFloatingWindow(DockingManager manager, DockableContent content) : this(manager) { //create a new temporary pane FloatingDockablePane pane = new FloatingDockablePane(this); //setup window size //Width = content.ContainerPane.ActualWidth; //Height = content.ContainerPane.ActualHeight; if (content.FloatingWindowSize.IsEmpty) content.FloatingWindowSize = new Size(content.ContainerPane.ActualWidth, content.ContainerPane.ActualHeight); Width = content.FloatingWindowSize.Width; Height = content.FloatingWindowSize.Height; //save current content position in container pane _previousPane = content.ContainerPane; _arrayIndexPreviousPane = _previousPane.Items.IndexOf(content); - - //pane.SetValue(ResizingPanel.ResizeWidthProperty, _previousPane.GetValue(ResizingPanel.ResizeWidthProperty)); - //pane.SetValue(ResizingPanel.ResizeHeightProperty, _previousPane.GetValue(ResizingPanel.ResizeHeightProperty)); + pane.Style = content.ContainerPane.Style; //remove content from container pane content.ContainerPane.RemoveContent(_arrayIndexPreviousPane); //add content to my temporary pane pane.Items.Add(content); //let templates access this pane HostedPane = pane; //Change state on contents IsDockableWindow = true; DocumentPane originalDocumentPane = _previousPane as DocumentPane; if (originalDocumentPane != null) originalDocumentPane.CheckContentsEmpty(); } public DockableFloatingWindow(DockingManager manager, DockablePane dockablePane) : this(manager) { //create a new temporary pane FloatingDockablePane pane = new FloatingDockablePane(this); //setup window size ManagedContent selectedContent = dockablePane.SelectedItem as ManagedContent; if (selectedContent != null && selectedContent.FloatingWindowSize.IsEmpty) selectedContent.FloatingWindowSize = new Size(dockablePane.ActualWidth, dockablePane.ActualHeight); if (selectedContent != null) { Width = selectedContent.FloatingWindowSize.Width; Height = selectedContent.FloatingWindowSize.Height; this.ResizeMode = selectedContent.FloatingResizeMode; } else { Width = dockablePane.ActualWidth; Height = dockablePane.ActualHeight; } + //transfer the style from the original dockablepane + pane.Style = dockablePane.Style; //Width = dockablePane.ActualWidth; //Height = dockablePane.ActualHeight; ////save current content position in container pane //pane.SetValue(ResizingPanel.ResizeWidthProperty, dockablePane.GetValue(ResizingPanel.ResizeWidthProperty)); //pane.SetValue(ResizingPanel.ResizeHeightProperty, dockablePane.GetValue(ResizingPanel.ResizeHeightProperty)); int selectedIndex = dockablePane.SelectedIndex; //remove contents from container pane and insert in hosted pane while (dockablePane.Items.Count > 0) { ManagedContent content = dockablePane.RemoveContent(0); //add content to my temporary pane pane.Items.Add(content); } //let templates access this pane HostedPane = pane; HostedPane.SelectedIndex = selectedIndex; //Change state on contents IsDockableWindow = true; } protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); if (HostedPane == null) HostedPane = Content as FloatingDockablePane; if (HostedPane != null) { Content = HostedPane; } } protected override void OnClosed(EventArgs e) { base.OnClosed(e); DockableContent[] cntsToClose = new DockableContent[HostedPane.Items.Count]; HostedPane.Items.CopyTo(cntsToClose, 0); foreach (DockableContent cntToClose in cntsToClose) { HostedPane.CloseOrHide(HostedPane.Items[0] as DockableContent, ForcedClosing); } Manager.UnregisterFloatingWindow(this); } public override Pane ClonePane() { DockablePane paneToAnchor = new DockablePane(); - //transfer the resizing panel sizes - //paneToAnchor.SetValue(ResizingPanel.ResizeWidthProperty, - // HostedPane.GetValue(ResizingPanel.ResizeWidthProperty)); - //paneToAnchor.SetValue(ResizingPanel.ResizeHeightProperty, - // HostedPane.GetValue(ResizingPanel.ResizeHeightProperty)); ResizingPanel.SetEffectiveSize(paneToAnchor, new Size(Width, Height)); + if (HostedPane.Style != null) + paneToAnchor.Style = HostedPane.Style; int selectedIndex = HostedPane.SelectedIndex; //transfer contents from hosted pane in the floating window and //the new created dockable pane while (HostedPane.Items.Count > 0) { paneToAnchor.Items.Add( HostedPane.RemoveContent(0)); } paneToAnchor.SelectedIndex = selectedIndex; return paneToAnchor; } protected override void OnExecuteCommand(object sender, ExecutedRoutedEventArgs e) { if (e.Command == TabbedDocumentCommand) { DockableContent currentContent = HostedPane.SelectedItem as DockableContent; Manager.MainDocumentPane.Items.Insert(0, HostedPane.RemoveContent(HostedPane.SelectedIndex)); Manager.MainDocumentPane.SelectedIndex = 0; currentContent.SetStateToDocument(); if (HostedPane.Items.Count == 0) this.Close(); e.Handled = true; } else if (e.Command == CloseCommand) { //DockableContent currentContent = HostedPane.SelectedItem as DockableContent; //Manager.Hide(currentContent); HostedPane.CloseOrHide(); if (HostedPane.Items.Count == 0) this.Close(); e.Handled = true; } base.OnExecuteCommand(sender, e); } protected override void Redock() { if (_previousPane != null) { if (_previousPane.GetManager() == null) { DockablePane newContainerPane = new DockablePane(); newContainerPane.Items.Add(HostedPane.RemoveContent(0)); newContainerPane.SetValue(ResizingPanel.ResizeWidthProperty, _previousPane.GetValue(ResizingPanel.ResizeWidthProperty)); newContainerPane.SetValue(ResizingPanel.ResizeHeightProperty, _previousPane.GetValue(ResizingPanel.ResizeHeightProperty)); + + if (_previousPane.Style != null) + newContainerPane.Style = _previousPane.Style; + Manager.Anchor(newContainerPane, ((DockablePane)_previousPane).Anchor); } else { if (_arrayIndexPreviousPane > _previousPane.Items.Count) _arrayIndexPreviousPane = _previousPane.Items.Count; DockableContent currentContent = HostedPane.Items[0] as DockableContent; _previousPane.Items.Insert(_arrayIndexPreviousPane, HostedPane.RemoveContent(0)); _previousPane.SelectedIndex = _arrayIndexPreviousPane; currentContent.SetStateToDock(); } this.Close(); } base.Redock(); } } } diff --git a/AvalonDock/AvalonDock/DockableTabPanel.cs b/AvalonDock/AvalonDock/DockableTabPanel.cs index 8a4b67f..5c684a7 100644 --- a/AvalonDock/AvalonDock/DockableTabPanel.cs +++ b/AvalonDock/AvalonDock/DockableTabPanel.cs @@ -1,113 +1,113 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace AvalonDock { public class DockableTabPanel : PaneTabPanel { protected override Size MeasureOverride(Size availableSize) { double totWidth = 0; //double maxHeight = 0; if (Children.Count == 0) return base.MeasureOverride(availableSize); List<UIElement> childsOrderedByWidth = new List<UIElement>(); - foreach (DockableContent child in Children) + foreach (FrameworkElement child in Children) { child.Width = double.NaN; child.Height = double.NaN; child.Measure(new Size(double.PositiveInfinity, availableSize.Height)); totWidth += child.DesiredSize.Width; childsOrderedByWidth.Add(child); } if (totWidth > availableSize.Width) { childsOrderedByWidth.Sort(delegate(UIElement elem1, UIElement elem2) { return elem2.DesiredSize.Width.CompareTo(elem1.DesiredSize.Width); }); int i = childsOrderedByWidth.Count - 1; double sumWidth = 0; while (childsOrderedByWidth[i].DesiredSize.Width * (i + 1) + sumWidth < availableSize.Width) { sumWidth += childsOrderedByWidth[i].DesiredSize.Width; i--; if (i < 0) break; } double shWidth = (availableSize.Width - sumWidth) / (i + 1); foreach (UIElement child in Children) { if (shWidth < child.DesiredSize.Width) child.Measure(new Size(shWidth, availableSize.Height)); } } return base.MeasureOverride(availableSize); } protected override Size ArrangeOverride(Size finalSize) { double offsetX = 0; foreach (FrameworkElement child in Children) { double childFinalWidth = child.DesiredSize.Width; child.Arrange(new Rect(offsetX, 0, childFinalWidth, finalSize.Height)); offsetX += childFinalWidth; } return base.ArrangeOverride(finalSize); } } } diff --git a/AvalonDock/AvalonDock/DocumentPane.cs b/AvalonDock/AvalonDock/DocumentPane.cs index 68c4a11..47379a0 100644 --- a/AvalonDock/AvalonDock/DocumentPane.cs +++ b/AvalonDock/AvalonDock/DocumentPane.cs @@ -1,517 +1,520 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Diagnostics; namespace AvalonDock { public class DocumentPane : Pane { static DocumentPane() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml DefaultStyleKeyProperty.OverrideMetadata(typeof(DocumentPane), new FrameworkPropertyMetadata(typeof(DocumentPane))); } public DocumentPane() { this.Loaded += new RoutedEventHandler(DocumentPane_Loaded); } void DocumentPane_Loaded(object sender, RoutedEventArgs e) { + if (Parent == null) + return; + if (GetManager() == null) throw new InvalidOperationException("DocumentPane must be put under a DockingManager!"); //try to set this as main document pane if (GetManager().MainDocumentPane == null) { GetManager().MainDocumentPane = this; NotifyPropertyChanged("IsMainDocumentPane"); } else { //or ensure that this document pane is under or at the same level of the MainDocumentPane GetManager().EnsurePanePositionIsValid(this); } } public bool? IsMainDocumentPane { get { if (GetManager() == null) return null; return GetManager().MainDocumentPane == this; } } protected override void OnInitialized(EventArgs e) { this.CommandBindings.Add( new CommandBinding(ShowDocumentsListMenuCommand, ExecutedShowDocumentsListMenuCommand, CanExecuteShowDocumentsListMenuCommand)); this.CommandBindings.Add( new CommandBinding(ApplicationCommands.Close, ExecutedCloseCommand, CanExecuteCloseCommand)); this.CommandBindings.Add( new CommandBinding(CloseCommand, ExecutedCloseCommand, CanExecuteCloseCommand)); this.CommandBindings.Add( new CommandBinding(CloseAllButThisCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(NewHorizontalTabGroupCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(NewVerticalTabGroupCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); base.OnInitialized(e); } #region DocumentPane Commands #region Show Document Window List Command public static RoutedCommand ShowDocumentsListMenuCommand = new RoutedCommand(); public void ExecutedShowDocumentsListMenuCommand(object sender, ExecutedRoutedEventArgs e) { //MessageBox.Show("ShowOptionsMenu"); ShowDocumentsListMenu(this, null); } public void CanExecuteShowDocumentsListMenuCommand(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } #endregion #region Close Command //ApplicationCommands.Close command.... public void ExecutedCloseCommand(object sender, ExecutedRoutedEventArgs e) { if (GetManager() == null) return; ManagedContent contentToClose = SelectedItem as ManagedContent; if (e.Parameter is ManagedContent) contentToClose = e.Parameter as ManagedContent; DockableContent dockableContent = contentToClose as DockableContent; if (dockableContent != null) CloseOrHide(dockableContent); else { DocumentContent documentContent = contentToClose as DocumentContent; documentContent.Close(); //if (documentContent != null) // Items.Remove(documentContent); //CheckContentsEmpty(); } } public void CanExecuteCloseCommand(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } #endregion #region Activate Document Command public static RoutedCommand ActivateDocumentCommand = new RoutedCommand(); public void ExecutedActivateDocumentCommand(object sender, ExecutedRoutedEventArgs e) { ManagedContent doc = e.Parameter as ManagedContent; if (doc != null) { if (!DocumentTabPanel.GetIsHeaderVisible(doc)) { DocumentPane parentPane = doc.ContainerPane as DocumentPane; parentPane.Items.Remove(doc); parentPane.Items.Insert(0, doc); } ////doc.IsSelected = true; ////Selector.SetIsSelected(doc, true); //if (this.GetManager() != null) // this.GetManager().ActiveContent = doc; doc.SetAsActive(); } } public void CanExecuteActivateDocumentCommand(object sender, CanExecuteRoutedEventArgs e) { //ManagedContent doc = e.Parameter as ManagedContent; //if (doc != null && !doc.IsSelected) e.CanExecute = true; } #endregion #region Commands private static object syncRoot = new object(); private static RoutedUICommand closeAllButThisCommand = null; public static RoutedUICommand CloseAllButThisCommand { get { lock (syncRoot) { if (null == closeAllButThisCommand) { closeAllButThisCommand = new RoutedUICommand("Close All But This", "CloseAllButThis", typeof(DocumentPane)); } } return closeAllButThisCommand; } } private static RoutedUICommand closeCommand = null; public static RoutedUICommand CloseCommand { get { lock (syncRoot) { if (null == closeCommand) { closeCommand = new RoutedUICommand("C_lose", "Close", typeof(DocumentPane)); } } return closeCommand; } } private static RoutedUICommand newHTabGroupCommand = null; public static RoutedUICommand NewHorizontalTabGroupCommand { get { lock (syncRoot) { if (null == newHTabGroupCommand) { newHTabGroupCommand = new RoutedUICommand("New Horizontal Tab Group", "NewHorizontalTabGroup", typeof(DocumentPane)); } } return newHTabGroupCommand; } } private static RoutedUICommand newVTabGroupCommand = null; public static RoutedUICommand NewVerticalTabGroupCommand { get { lock (syncRoot) { if (null == newVTabGroupCommand) { newVTabGroupCommand = new RoutedUICommand("New Vertical Tab Group", "NewVerticalTabGroup", typeof(DocumentPane)); } } return newVTabGroupCommand; } } internal virtual void OnExecuteCommand(object sender, ExecutedRoutedEventArgs e) { if (e.Command == CloseAllButThisCommand) { CloseAllButThis(); e.Handled = true; } else if (e.Command == NewHorizontalTabGroupCommand) { NewHorizontalTabGroup(); e.Handled = true; } else if (e.Command == NewVerticalTabGroupCommand) { NewVerticalTabGroup(); e.Handled = true; } } protected virtual void OnCanExecuteCommand(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = this.GetManager() != null; if (e.CanExecute) { if (e.Command == NewHorizontalTabGroupCommand || e.Command == NewVerticalTabGroupCommand) { if (this.Items.Count <= 1) e.CanExecute = false; } } } void CloseAllButThis() { DocumentContent activeContent = GetManager().ActiveDocument as DocumentContent; foreach (DocumentContent cnt in this.GetManager().Documents) { if (cnt != activeContent) cnt.Close(); } } void NewHorizontalTabGroup() { ManagedContent activeContent = SelectedItem as ManagedContent; DocumentPane newContainerPane = new DocumentPane(); int indexOfDocumentInItsContainer = activeContent.ContainerPane.Items.IndexOf(activeContent); activeContent.ContainerPane.RemoveContent(indexOfDocumentInItsContainer); newContainerPane.Items.Add(activeContent); GetManager().Anchor(newContainerPane, this, AnchorStyle.Bottom); } void NewVerticalTabGroup() { ManagedContent activeContent = SelectedItem as ManagedContent; DocumentPane newContainerPane = new DocumentPane(); int indexOfDocumentInItsContainer = activeContent.ContainerPane.Items.IndexOf(activeContent); activeContent.ContainerPane.RemoveContent(indexOfDocumentInItsContainer); newContainerPane.Items.Add(activeContent); GetManager().Anchor(newContainerPane, this, AnchorStyle.Right); } #endregion #endregion UIElement _optionsContextMenuPlacementTarget; public override void OnApplyTemplate() { _optionsContextMenuPlacementTarget = GetTemplateChild("PART_ShowContextMenuButton") as UIElement; base.OnApplyTemplate(); } void ShowDocumentsListMenu(object sender, RoutedEventArgs e) { if (Items.Count == 0) return; //nothings to show ContextMenu cxMenuDocuments = (ContextMenu)FindResource("DocumentsListMenu"); if (cxMenuDocuments != null) { cxMenuDocuments.ItemsSource = Items; cxMenuDocuments.CommandBindings.Add(new CommandBinding(ActivateDocumentCommand, new ExecutedRoutedEventHandler(this.ExecutedActivateDocumentCommand), new CanExecuteRoutedEventHandler(CanExecuteActivateDocumentCommand))); if (_optionsContextMenuPlacementTarget != null) { cxMenuDocuments.Placement = PlacementMode.Bottom; cxMenuDocuments.PlacementTarget = _optionsContextMenuPlacementTarget; } else { cxMenuDocuments.Placement = PlacementMode.MousePoint; cxMenuDocuments.PlacementTarget = this; } cxMenuDocuments.IsOpen = true; } } public override bool IsSurfaceVisible { get { if (IsMainDocumentPane.HasValue && !IsMainDocumentPane.Value && Items.Count == 0) return false; return true; } } protected override void OnMouseDown(MouseButtonEventArgs e) { base.OnMouseDown(e); if (!e.Handled) { if (_partHeader != null && !_partHeader.IsMouseOver) { //prevent document content to start dragging when it is clicked outside of the header area e.Handled = true; } } } internal void CheckContentsEmpty() { if (Items.Count == 0) { bool isMainDocPaneToBeClose = IsMainDocumentPane.HasValue && IsMainDocumentPane.Value; if (isMainDocPaneToBeClose) { DockingManager manager = GetManager(); DocumentPane candidateNewMainDocPane = manager.FindAnotherLogicalChildContained<DocumentPane>(this); if (candidateNewMainDocPane != null) { ResizingPanel containerPanel = Parent as ResizingPanel; if (containerPanel != null) containerPanel.RemoveChild(this); manager.MainDocumentPane = candidateNewMainDocPane; candidateNewMainDocPane.NotifyPropertyChanged("IsMainDocumentPane"); } } else { ResizingPanel containerPanel = Parent as ResizingPanel; if (containerPanel != null) containerPanel.RemoveChild(this); } } } internal override ResizingPanel GetContainerPanel() { return GetParentDocumentPaneResizingPanel(); } internal DocumentPaneResizingPanel GetParentDocumentPaneResizingPanel() { ResizingPanel parentPanel = LogicalTreeHelper.GetParent(this) as ResizingPanel; if (parentPanel == null) return null; while (!(parentPanel is DocumentPaneResizingPanel)) { parentPanel = LogicalTreeHelper.GetParent(parentPanel) as ResizingPanel; if (parentPanel == null) return null; } return parentPanel as DocumentPaneResizingPanel; } public override Rect SurfaceRectangle { get { //it is dragging a document let drop in this document pane if (GetManager().DragPaneServices.FloatingWindow is DocumentFloatingWindow) return base.SurfaceRectangle; //otherwise we should provide a drop surface for all the DocumentPaneResizingPanel DocumentPaneResizingPanel parentPanel = GetParentDocumentPaneResizingPanel(); if (parentPanel == null) return base.SurfaceRectangle; return new Rect(HelperFunc.PointToScreenWithoutFlowDirection(parentPanel, new Point(0, 0)), new Size(parentPanel.ActualWidth, parentPanel.ActualHeight)); //return new Rect(parentPanel.PointToScreen(new Point(0, 0)), new Size(parentPanel.ActualWidth, parentPanel.ActualHeight)); } } protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (e.NewItems != null) { foreach (object newItem in e.NewItems) { if (!(newItem is DockableContent) && !(newItem is DocumentContent)) throw new InvalidOperationException("DocumentPane can contain only DockableContents or DocumentContents!"); if (newItem is DockableContent && (((DockableContent)newItem).DockableStyle & DockableStyle.Document) == 0) { ((DockableContent)newItem).DockableStyle |= DockableStyle.Document; } } } base.OnItemsChanged(e); } protected override void OnSelectionChanged(SelectionChangedEventArgs e) { ManagedContent selectedContent = this.SelectedItem as ManagedContent; if (selectedContent != null && GetManager() != null) GetManager().ActiveDocument = selectedContent; base.OnSelectionChanged(e); } } } diff --git a/AvalonDock/AvalonDock/FlyoutDockablePane.cs b/AvalonDock/AvalonDock/FlyoutDockablePane.cs index a09404b..6b75057 100644 --- a/AvalonDock/AvalonDock/FlyoutDockablePane.cs +++ b/AvalonDock/AvalonDock/FlyoutDockablePane.cs @@ -1,111 +1,113 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Input; namespace AvalonDock { internal class FlyoutDockablePane : DockablePane { static FlyoutDockablePane() { DockablePane.ShowTabsProperty.AddOwner(typeof(FlyoutDockablePane), new FrameworkPropertyMetadata(false)); } int _arrayIndexPreviousPane = -1; public FlyoutDockablePane() { } public FlyoutDockablePane(DockableContent content) { _referencedPane = content.ContainerPane as DockablePane; _manager = _referencedPane.GetManager(); //save current content position in container pane _arrayIndexPreviousPane = _referencedPane.Items.IndexOf(content); Anchor = _referencedPane.Anchor; SetValue(ResizingPanel.ResizeWidthProperty, new GridLength(ResizingPanel.GetEffectiveSize(_referencedPane).Width)); SetValue(ResizingPanel.ResizeHeightProperty, new GridLength(ResizingPanel.GetEffectiveSize(_referencedPane).Height)); //if (double.IsInfinity(ResizingPanel.GetResizeWidth(this))) // ResizingPanel.SetResizeWidth(this, 200); //if (double.IsInfinity(ResizingPanel.GetResizeHeight(this))) // ResizingPanel.SetResizeHeight(this, 200); + this.Style = _referencedPane.Style; + //remove content from container pane //and add content to my temporary pane _referencedPane.Items.RemoveAt(_arrayIndexPreviousPane); this.Items.Add(content); //select the single content in this pane SelectedItem = this.Items[0]; } public override void OnApplyTemplate() { base.OnApplyTemplate(); } internal void RestoreOriginalPane() { if (this.Items.Count == 1) { _referencedPane.Items.Insert(_arrayIndexPreviousPane, RemoveContent(0)); ResizingPanel.SetResizeWidth(_referencedPane, ResizingPanel.GetResizeWidth(this)); ResizingPanel.SetResizeHeight(_referencedPane, ResizingPanel.GetResizeHeight(this)); } } DockablePane _referencedPane = null; DockingManager _manager = null; public override DockingManager GetManager() { return _manager; } internal override void ToggleAutoHide() { GetManager().ToggleAutoHide(_referencedPane); } //internal override void Close() //{ // DockingManager manager = GetManager(); // if (manager != null) // Manager.Hide(SelectedItem as DockableContent); //} } } diff --git a/AvalonDock/AvalonDock/ManagedContent.cs b/AvalonDock/AvalonDock/ManagedContent.cs index c005bf9..f81f08f 100644 --- a/AvalonDock/AvalonDock/ManagedContent.cs +++ b/AvalonDock/AvalonDock/ManagedContent.cs @@ -1,558 +1,559 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.ComponentModel; using System.Xml; using System.Windows.Forms.Integration; using System.Diagnostics; using System.Windows.Threading; using System.Threading; using System.Reflection; namespace AvalonDock { public abstract class ManagedContent : ContentControl, INotifyPropertyChanged { static ManagedContent() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml //DefaultStyleKeyProperty.OverrideMetadata(typeof(ManagedContent), new FrameworkPropertyMetadata(typeof(ManagedContent))); FocusableProperty.OverrideMetadata(typeof(ManagedContent), new FrameworkPropertyMetadata(true)); } public ManagedContent() { this.Loaded += new RoutedEventHandler(ManagedContent_Loaded); this.Unloaded += new RoutedEventHandler(ManagedContent_Unloaded); this.LayoutUpdated += new EventHandler(ManagedContent_LayoutUpdated); } public void ManagedContent_LayoutUpdated(object sender, EventArgs e) { WindowsFormsHost contentHost = null; if (this.Content is UserControl) { UserControl usTemp = this.Content as UserControl; if (usTemp.Content is WindowsFormsHost) contentHost = usTemp.Content as WindowsFormsHost; } else if (this.Content is WindowsFormsHost) { contentHost = this.Content as WindowsFormsHost; } if (contentHost != null) { object childCtrl = contentHost.GetType().GetProperty("Child").GetValue(contentHost, null); if (childCtrl != null) { - childCtrl.CallMethod("Refresh", null); + //childCtrl.CallMethod("Refresh", null); + this.Dispatcher.Invoke(new Action<object>((o) => o.CallMethod("Refresh", null)), DispatcherPriority.Render, childCtrl); } } } void ManagedContent_Loaded(object sender, RoutedEventArgs e) { } void ManagedContent_Unloaded(object sender, RoutedEventArgs e) { } public string Title { get { return (string)GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } // Using a DependencyProperty as the backing store for Title. This enables animation, styling, binding, etc... public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(ManagedContent)); //public string IconSource //{ // get { return (string)GetValue(IconSourceProperty); } // set { SetValue(IconSourceProperty, value); } //} //// Using a DependencyProperty as the backing store for Icon. This enables animation, styling, binding, etc... //public static readonly DependencyProperty IconSourceProperty = // DependencyProperty.Register("IconSource", typeof(string), typeof(ManagedContent)); /// <summary> /// Access to <see cref="IconProperty"/> dependency property /// </summary> public object Icon { get { return (object)GetValue(IconProperty); } set { SetValue(IconProperty, value); } } /// <summary> /// Select an icon object for the content /// </summary> public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(object), typeof(ManagedContent), new FrameworkPropertyMetadata(null, new CoerceValueCallback(OnCoerce_Icon))); private static object OnCoerce_Icon(DependencyObject o, object value) { if (value is string) { Uri iconUri; // try to resolve given value as an absolute URI if (Uri.TryCreate(value as String, UriKind.RelativeOrAbsolute, out iconUri)) { ImageSource img = new BitmapImage(iconUri); if (null != img) { GreyableImage icon = (o as ManagedContent).Icon as GreyableImage; if (null == icon) icon = new GreyableImage(); icon.Source = img; icon.Stretch = Stretch.None; icon.SnapsToDevicePixels = true; return icon; } } } return value; } /// <summary> /// Access to <see cref="DefaultFocusedElementProperty"/> /// </summary> public IInputElement DefaultElement { get { return (IInputElement)GetValue(DefaultFocusedElementProperty); } set { SetValue(DefaultFocusedElementProperty, value); } } /// <summary> /// Gets or sets an element which is focused by default when content is activated /// </summary> public static readonly DependencyProperty DefaultFocusedElementProperty = DependencyProperty.Register("DefaultElement", typeof(IInputElement), typeof(ManagedContent)); FrameworkElement _dragEnabledArea; protected FrameworkElement DragEnabledArea { get { return _dragEnabledArea; } } public override void OnApplyTemplate() { base.OnApplyTemplate(); _dragEnabledArea = GetTemplateChild("PART_DragArea") as FrameworkElement; if (_dragEnabledArea != null) { _dragEnabledArea.MouseDown += new MouseButtonEventHandler(OnDragMouseDown); _dragEnabledArea.MouseMove += new MouseEventHandler(OnDragMouseMove); _dragEnabledArea.MouseUp += new MouseButtonEventHandler(OnDragMouseUp); _dragEnabledArea.MouseLeave += new MouseEventHandler(OnDragMouseLeave); } } #region Mouse management protected virtual void OnDragStart(Point ptMouse, Point ptrelativeMouse) { } Point ptStartDrag; bool isMouseDown = false; protected Point StartDragPoint { get { return ptStartDrag; } } protected bool IsMouseDown { get { return isMouseDown; } } protected void ResetIsMouseDownFlag() { isMouseDown = false; } protected virtual void OnDragMouseDown(object sender, MouseButtonEventArgs e) { if (!e.Handled && Manager != null)// && State != DockableContentState.AutoHide) { isMouseDown = true; ptStartDrag = e.GetPosition((IInputElement)System.Windows.Media.VisualTreeHelper.GetParent(this)); } } protected virtual void OnDragMouseMove(object sender, MouseEventArgs e) { } protected virtual void OnDragMouseUp(object sender, MouseButtonEventArgs e) { isMouseDown = false; } Point ptRelativePosition; protected virtual void OnDragMouseLeave(object sender, MouseEventArgs e) { if (!e.Handled && IsMouseDown && Manager != null) { if (!IsMouseCaptured) { Point ptMouseMove = e.GetPosition(this); ManagedContent contentToSwap = null; if (ContainerPane != null) { foreach (ManagedContent content in ContainerPane.Items) { if (content == this) continue; HitTestResult res = VisualTreeHelper.HitTest(content, e.GetPosition(content)); if (res != null) { contentToSwap = content; break; } } } if (contentToSwap != null) { Pane containerPane = ContainerPane; int myIndex = containerPane.Items.IndexOf(this); ContainerPane.Items.RemoveAt(myIndex); int otherIndex = containerPane.Items.IndexOf(contentToSwap); containerPane.Items.RemoveAt(otherIndex); containerPane.Items.Insert(otherIndex, this); containerPane.Items.Insert(myIndex, contentToSwap); containerPane.SelectedItem = this; e.Handled = false; return; } else if (Math.Abs(ptMouseMove.X - StartDragPoint.X) > SystemParameters.MinimumHorizontalDragDistance || Math.Abs(ptMouseMove.Y - StartDragPoint.Y) > SystemParameters.MinimumVerticalDragDistance) { ptRelativePosition = e.GetPosition(DragEnabledArea); ResetIsMouseDownFlag(); OnDragStart(StartDragPoint, ptRelativePosition); e.Handled = true; } } } isMouseDown = false; } #endregion protected override void OnMouseDown(MouseButtonEventArgs e) { base.OnMouseDown(e); if (!e.Handled) { SetAsActive(); IInputElement focusedElement = e.Source as IInputElement; if (focusedElement != null) Keyboard.Focus(focusedElement); } } protected override void OnKeyDown(KeyEventArgs e) { if (e.Key == Key.Enter) { if (ContainerPane != null) ContainerPane.SelectedItem = this; } base.OnKeyDown(e); } public Pane ContainerPane { get { Pane containerPane = Parent as Pane; if (containerPane != null) return containerPane; return this.FindVisualAncestor<Pane>(false); } } internal DockingManager Manager { get { if (ContainerPane != null) return ContainerPane.GetManager(); return null; } } protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e) { base.OnGotKeyboardFocus(e); Debug.WriteLine(string.Format("[{0}].OnGotKeyboardFocus() Source={1} NewFocus={2} OldFocus={3}", this.Name, e.Source.GetType().ToString(), e.NewFocus.GetType().ToString(), e.OldFocus == null ? "<null>" : e.OldFocus.GetType().ToString())); if (Manager != null && this.IsKeyboardFocusWithin)// && Manager.ActiveContent != this) { Manager.ActiveContent = this; } } protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e) { Debug.WriteLine(string.Format("[{0}].OnLostKeyboardFocus() Source={1} NewFocus={2} OldFocus={3}", this.Name, e.Source.GetType().ToString(), e.NewFocus == null ? "<null>" : e.NewFocus.GetType().ToString(), e.OldFocus == null ? "<null>" : e.OldFocus.GetType().ToString())); base.OnLostKeyboardFocus(e); } bool _isActiveContent = false; /// <summary> /// Returns true if the content is the currently active content. /// </summary> /// <remarks>Use <see cref="SetAsActive"/> method to set a content as active.</remarks> public bool IsActiveContent { get { return _isActiveContent; } internal set { if (_isActiveContent != value) { _isActiveContent = value; NotifyPropertyChanged("IsActiveContent"); if (IsActiveContentChanged != null) IsActiveContentChanged(this, EventArgs.Empty); if (_isActiveContent && !IsKeyboardFocused) { Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(delegate { if (_isActiveContent && !IsKeyboardFocused) { if (this.Content is WindowsFormsHost) { //Use reflection in order to remove WinForms assembly reference WindowsFormsHost contentHost = this.Content as WindowsFormsHost; object childCtrl = contentHost.GetType().GetProperty("Child").GetValue(contentHost, null); if (childCtrl != null) { if (!childCtrl.GetPropertyValue<bool>("Focused")) { childCtrl.CallMethod("Focus", null); } } } else if (DefaultElement != null) { Debug.WriteLine("Try to set kb focus to " + DefaultElement); IInputElement kbFocused = Keyboard.Focus(DefaultElement); if (kbFocused != null) Debug.WriteLine("Focused element " + kbFocused); else Debug.WriteLine("No focused element"); } else if (this.Content is IInputElement) { //Debug.WriteLine("Try to set kb focus to " + this.Content.ToString()); //IInputElement kbFocused = Keyboard.Focus(this.Content as IInputElement); //if (kbFocused != null) // Debug.WriteLine("Focused element " + kbFocused); //else // Debug.WriteLine("No focused element"); } } })); } } } } public event EventHandler IsActiveContentChanged; /// <summary> /// Set the content as the active content /// </summary> /// <remarks>After this method returns property <see cref="IsActiveContent"/> returns true.</remarks> public void SetAsActive() { if (ContainerPane != null && Manager != null)// && Manager.ActiveContent != this) { ContainerPane.SelectedItem = this; ContainerPane.Focus(); if (Manager != null) Manager.ActiveContent = this; } } bool _isActiveDocument = false; /// <summary> /// Returns true if the document is the currently active document. /// </summary> /// <remarks>Use <see cref="SetAsActive"/> method to set a content as active.</remarks> public bool IsActiveDocument { get { return _isActiveDocument; } internal set { if (_isActiveDocument != value) { if (value) { if (ContainerPane != null) ContainerPane.SelectedItem = this; } _isActiveDocument = value; NotifyPropertyChanged("IsActiveDocument"); } } } bool _isLocked; /// <summary> /// Gets or sets a value indicating if this content is locked (readonly). /// </summary> public bool IsLocked { get { return _isLocked; } set { _isLocked = value; NotifyPropertyChanged("IsLocked"); } } Size _floatingWindowSize = Size.Empty; /// <summary> /// Gets or sets the size of the floating window which hosts this content /// </summary> public Size FloatingWindowSize { get { return _floatingWindowSize; } set { _floatingWindowSize = value; } } ResizeMode _floatingResizeMode = ResizeMode.CanResize; public ResizeMode FloatingResizeMode { get { return _floatingResizeMode; } set { _floatingResizeMode = value; } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion public bool IsCloseable { get { return (bool)GetValue(IsCloseableProperty); } set { SetValue(IsCloseableProperty, value); } } // Using a DependencyProperty as the backing store for IsCloseable. This enables animation, styling, binding, etc... public static readonly DependencyProperty IsCloseableProperty = DependencyProperty.Register("IsCloseable", typeof(bool), typeof(ManagedContent), new UIPropertyMetadata(true)); } } diff --git a/AvalonDock/AvalonDock/Properties/AssemblyInfo.cs b/AvalonDock/AvalonDock/Properties/AssemblyInfo.cs index 5eb5647..6b9b298 100644 --- a/AvalonDock/AvalonDock/Properties/AssemblyInfo.cs +++ b/AvalonDock/AvalonDock/Properties/AssemblyInfo.cs @@ -1,62 +1,62 @@ #region Using directives using System.Reflection; using System.Runtime.CompilerServices; using System.Resources; using System.Globalization; using System.Windows; using System.Runtime.InteropServices; #endregion // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AvalonDock")] [assembly: AssemblyDescription("WPF docking library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AvalonDock")] [assembly: AssemblyCopyright("Copyright @ Adolfo Marinucci 2007-2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] // Specifies the location in which theme dictionaries are stored for types in an assembly. [assembly: ThemeInfo( // Specifies the location of system theme-specific resource dictionaries for this project. // The default setting in this project is "None" since this default project does not // include these user-defined theme files: // Themes\Aero.NormalColor.xaml // Themes\Classic.xaml // Themes\Luna.Homestead.xaml // Themes\Luna.Metallic.xaml // Themes\Luna.NormalColor.xaml // Themes\Royale.NormalColor.xaml ResourceDictionaryLocation.SourceAssembly, // Specifies the location of the system non-theme specific resource dictionary: // Themes\generic.xaml ResourceDictionaryLocation.SourceAssembly)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: -[assembly: AssemblyVersion("1.2.2691")] +[assembly: AssemblyVersion("1.2.2702")]
icsharpcode/SharpDevelop-Vendor
638dbd5782d7224f742dcd2ebe0ecfb867645479
Upload AvalonDock 1.2.2691 to vendor branch.
diff --git a/AvalonDock/AvalonDock/DockableContent.cs b/AvalonDock/AvalonDock/DockableContent.cs index 4ca992b..ee17967 100644 --- a/AvalonDock/AvalonDock/DockableContent.cs +++ b/AvalonDock/AvalonDock/DockableContent.cs @@ -1,571 +1,581 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Diagnostics; using System.Xml; namespace AvalonDock { /// <summary> /// Enumerates all the possible states of <see cref="DockableContent"/> /// </summary> public enum DockableContentState { /// <summary> /// Content is docked to a border of a <see cref="ResizingPanel"/> within as <see cref="DockingManager"/> control /// </summary> Docked, /// <summary> /// Content is hosted by a flyout window and is visible only when user move mouse over an anchor thumb located to a <see cref="DockingManager"/> controlo border /// </summary> AutoHide, /// <summary> /// Content is hosted by a floating window and user can redock is on its <see cref="DockingManager"/> container control /// </summary> DockableWindow, /// <summary> /// Content is hosted by a floating window that can't be docked to a its <see cref="DockingManager"/> container control /// </summary> FloatingWindow, /// <summary> /// Content is hosted into a <see cref="DocmumentPane"/> /// </summary> Document, /// <summary> /// Content is hidden /// </summary> Hidden, } /// <summary> /// Defines how a dockable content can be dragged over a docking manager /// </summary> /// <remarks>This style can be composed with the 'or' operator.</remarks> public enum DockableStyle : uint { /// <summary> /// Content is not dockable at all /// </summary> None = 0x0000, /// <summary> /// Dockable as document /// </summary> Document = 0x0001, /// <summary> /// Dockable to the left border of <see cref="DockingManager"/> /// </summary> LeftBorder = 0x0002, /// <summary> /// Dockable to the right border of <see cref="DockingManager"/> /// </summary> RightBorder = 0x0004, /// <summary> /// Dockable to the top border of <see cref="DockingManager"/> /// </summary> TopBorder = 0x0008, /// <summary> /// Dockable to the bottom border of <see cref="DockingManager"/> /// </summary> BottomBorder= 0x0010, /// <summary> /// A <see cref="DockableContent"/> with this style can be hosted in a <see cref="FloatingWindow"/> /// </summary> Floating = 0x0020, /// <summary> /// A <see cref="DockableContent"/> with this style can be the only one content in a <see cref="DockablePane"/> pane (NOT YET SUPPORTED) /// </summary> /// <remarks>This style is not compatible with <see cref="DockableStyle.Document"/> style</remarks> Single = 0x0040, /// <summary> /// A <see cref="DockableContet"/> with this style can be autohidden. /// </summary> AutoHide = 0x0080, /// <summary> /// Dockable only to a border of a <see cref="DockingManager"/> /// </summary> DockableToBorders = LeftBorder | RightBorder | TopBorder | BottomBorder | AutoHide, /// <summary> /// Dockable to a border of a <see cref="DockingManager"/> and into a <see cref="DocumentPane"/> /// </summary> Dockable = DockableToBorders | Document | Floating, /// <summary> /// Dockable to a border of a <see cref="DockingManager"/> and into a <see cref="DocumentPane"/> but not in autohidden mode (WinForms controls) /// </summary> DockableButNotAutoHidden = Dockable & ~AutoHide } /// <summary> /// Represent a state of a dockable content that can be used to restore it after it's hidden /// </summary> internal class DockableContentStateAndPosition { public readonly Pane ContainerPane = null; public readonly int ChildIndex = -1; public readonly double Width; public readonly double Height; - + public readonly DockableContentState State; public readonly AnchorStyle Anchor = AnchorStyle.None; public DockableContentStateAndPosition( Pane containerPane, int childIndex, double width, double height, - AnchorStyle anchor) + AnchorStyle anchor, + DockableContentState state) { ContainerPane = containerPane; ChildIndex = childIndex; Width = Math.Max(width, 100.0); Height = Math.Max(height, 100.0); Anchor = anchor; + State = state; } public DockableContentStateAndPosition( DockableContent cntToSave) { ContainerPane = cntToSave.ContainerPane; ChildIndex = ContainerPane.Items.IndexOf(cntToSave); Width = Math.Max(ContainerPane.ActualWidth, 100.0); Height = Math.Max(ContainerPane.ActualHeight, 100.0); + State = cntToSave.State; DockablePane dockablePane = ContainerPane as DockablePane; if (dockablePane != null) { Anchor = dockablePane.Anchor; } } } /// <summary> /// Identifies a content that can be drag over a <see cref="DockingManager"/> control or hosted by a window floating over it (<see cref="FloatingWindow"/>). /// </summary> public class DockableContent : ManagedContent { static DockableContent() { - DefaultStyleKeyProperty.OverrideMetadata(typeof(DockableContent), new FrameworkPropertyMetadata(typeof(DockableContent))); + //DefaultStyleKeyProperty.OverrideMetadata(typeof(DockableContent), new FrameworkPropertyMetadata(typeof(DockableContent))); } public DockableContent() { } #region Drag content protected override void OnDragMouseMove(object sender, MouseEventArgs e) { base.OnDragMouseMove(sender, e); } protected override void OnDragStart(Point ptMouse, Point ptRelativeMouse) { if (DockableStyle != DockableStyle.None && State != DockableContentState.AutoHide) { Manager.Drag(this, HelperFunc.PointToScreenWithoutFlowDirection(this, ptMouse), ptRelativeMouse); } base.OnDragStart(ptMouse, ptRelativeMouse); } #endregion #region State Properties & Events public delegate void DockableContentStateHandler(object sender, DockableContentState state); public event DockableContentStateHandler StateChanged; public DockableContentState State { get { return (DockableContentState)GetValue(StatePropertyKey.DependencyProperty); } //protected set { SetValue(StatePropertyKey, value); } protected set { SetValue(StatePropertyKey, value); if (StateChanged != null) StateChanged(this, value); } } // Using a DependencyProperty as the backing store for State. This enables animation, styling, binding, etc... public static readonly DependencyPropertyKey StatePropertyKey = DependencyProperty.RegisterReadOnly("State", typeof(DockableContentState), typeof(DockableContent), new UIPropertyMetadata(DockableContentState.Docked)); DockableStyle _dockableStyle = DockableStyle.Dockable; /// <summary> /// Get or sets a value that indicates how a dockable content can be dragged over and docked to a <see cref="DockingManager"/> /// </summary> public DockableStyle DockableStyle { get { return _dockableStyle; } set { _dockableStyle = value; } } #endregion #region StateMachine internal void SetStateToAutoHide() { State = DockableContentState.AutoHide; } internal void SetStateToDock() { State = DockableContentState.Docked; } internal void SetStateToDockableWindow() { if (State == DockableContentState.DockableWindow) return; Debug.Assert( State == DockableContentState.Document || State == DockableContentState.Docked || State == DockableContentState.FloatingWindow); State = DockableContentState.DockableWindow; } internal void SetStateToFloatingWindow() { if (State == DockableContentState.FloatingWindow) return; Debug.Assert( State == DockableContentState.Document || State == DockableContentState.Docked || State == DockableContentState.DockableWindow); State = DockableContentState.FloatingWindow; } internal void SetStateToHidden() { State = DockableContentState.Hidden; } internal void SetStateToDocument() { State = DockableContentState.Document; } #endregion #region HideOnClose public static DependencyProperty HideOnCloseKey = DependencyProperty.Register("HideOnClose", typeof(bool), typeof(DockableContent), new PropertyMetadata(true)); public bool HideOnClose { get { return (bool)GetValue(HideOnCloseKey); } set { SetValue(HideOnCloseKey, value); } } #endregion + + + + protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); this.CommandBindings.Add( new CommandBinding(FloatingCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(DockableCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(ShowAsDocumentCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(DockablePane.ToggleAutoHideCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(HideCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); } #region Commands static object syncRoot = new object(); private static RoutedUICommand documentCommand = null; public static RoutedUICommand ShowAsDocumentCommand { get { lock (syncRoot) { if (null == documentCommand) { documentCommand = new RoutedUICommand("Tabbed Document", "Document", typeof(DockableContent)); } } return documentCommand; } } private static RoutedUICommand dockableCommand = null; public static RoutedUICommand DockableCommand { get { lock (syncRoot) { if (null == dockableCommand) { dockableCommand = new RoutedUICommand("Dockable", "Dockable", typeof(DockablePane)); } } return dockableCommand; } } private static RoutedUICommand floatingCommand = null; public static RoutedUICommand FloatingCommand { get { lock (syncRoot) { if (null == floatingCommand) { floatingCommand = new RoutedUICommand("F_loating", "Floating", typeof(DockableContent)); } } return floatingCommand; } } private static RoutedUICommand hideCommand = null; public static RoutedUICommand HideCommand { get { lock (syncRoot) { if (null == hideCommand) { hideCommand = new RoutedUICommand("H_ide", "Hide", typeof(DockableContent)); } } return hideCommand; } } internal virtual void OnExecuteCommand(object sender, ExecutedRoutedEventArgs e) { if (!e.Handled && e.Command == DockablePane.ToggleAutoHideCommand) { if ((DockableStyle & DockableStyle.AutoHide) > 0) { ((ContainerPane as DockablePane)).ToggleAutoHide(); e.Handled = true; } } else if (!e.Handled && e.Command == DockableContent.HideCommand) { Manager.Hide(this); e.Handled = true; } else if (!e.Handled && e.Command == DockableContent.FloatingCommand) { Manager.Show(this, DockableContentState.FloatingWindow); e.Handled = true; } else if (!e.Handled && e.Command == DockableContent.DockableCommand) { Manager.Show(this, DockableContentState.DockableWindow); e.Handled = true; } else if (!e.Handled && e.Command == DockableContent.ShowAsDocumentCommand) { Manager.Show(this, DockableContentState.Document); e.Handled = true; } } protected virtual void OnCanExecuteCommand(object sender, CanExecuteRoutedEventArgs e) { if (State == DockableContentState.AutoHide) { if (e.Command == DockablePane.ToggleAutoHideCommand || e.Command == DockablePane.CloseCommand || e.Command == DockableContent.HideCommand) e.CanExecute = true; else e.CanExecute = false; } else e.CanExecute = true; } #endregion #region Operations on content /// <summary> /// Remove this content from its parent container pane /// </summary> /// <returns></returns> internal DockableContent DetachFromContainerPane() { if (ContainerPane != null) { int indexOfContent = ContainerPane.Items.IndexOf(this); return ContainerPane.RemoveContent(indexOfContent) as DockableContent; } return null; } DockableContentStateAndPosition _savedStateAndPosition = null; internal DockableContentStateAndPosition SavedStateAndPosition { get { return _savedStateAndPosition; } } internal void SaveCurrentStateAndPosition() { //if (State == DockableContentState.Docked) //{ _savedStateAndPosition = new DockableContentStateAndPosition( this); //} //else //{ // _savedStateAndPosition = null; //} } /// <summary> /// Reset internal state and position of the content /// </summary> /// <remarks>After a <see cref="DockableContent"/> is hidden AvalonDock save its state and position in order to /// restore it correctly when user wants to reshow it calling <see cref="DockingManager.Show"/> function. Call this method /// if you want to reset these data and provide your state and anchor style calling one of the overloads of the function /// <see cref="DockingManager.Show"/>.</remarks> public void ResetSavedStateAndPosition() { _savedStateAndPosition = null; } #endregion #region Save/Restore Content Layout /// <summary> /// Save content specific layout settings /// </summary> /// <param name="storeWriter">Backend store writer</param> /// <remarks>Custom derived class can overloads this method to handle custom layout persistence.</remarks> public virtual void SaveLayout(XmlWriter storeWriter) { if (!FloatingWindowSize.IsEmpty) { storeWriter.WriteAttributeString( "FloatingWindowSize", new SizeConverter().ConvertToInvariantString(FloatingWindowSize)); } if (SavedStateAndPosition != null) { storeWriter.WriteAttributeString( "ChildIndex", SavedStateAndPosition.ChildIndex.ToString()); storeWriter.WriteAttributeString( "Width", SavedStateAndPosition.Width.ToString()); storeWriter.WriteAttributeString( "Height", SavedStateAndPosition.Height.ToString()); storeWriter.WriteAttributeString( "Anchor", SavedStateAndPosition.Anchor.ToString()); + storeWriter.WriteAttributeString( + "State", SavedStateAndPosition.State.ToString()); } } /// <summary> /// Restore content specific layout settings /// </summary> /// <param name="storeReader">Saved xml element containg content layout settings</param> /// <remarks>Custom derived class must overload this method to restore custom layout settings previously saved trought <see cref="SaveLayout"/>.</remarks> public virtual void RestoreLayout(XmlElement contentElement) { if (contentElement.HasAttribute("FloatingWindowSize")) FloatingWindowSize = (Size)(new SizeConverter()).ConvertFromInvariantString(contentElement.GetAttribute("FloatingWindowSize")); Size effectiveSize = new Size(0d, 0d); if (contentElement.HasAttribute("EffectiveSize")) { // Store effectiveSize = (Size)(new SizeConverter()).ConvertFromInvariantString(contentElement.GetAttribute("EffectiveSize")); } ResizingPanel.SetEffectiveSize(this, effectiveSize); if (contentElement.HasAttribute("ChildIndex")) { _savedStateAndPosition = new DockableContentStateAndPosition( ContainerPane, int.Parse(contentElement.GetAttribute("ChildIndex")), double.Parse(contentElement.GetAttribute("Width")), double.Parse(contentElement.GetAttribute("Height")), - (AnchorStyle) Enum.Parse(typeof(AnchorStyle), contentElement.GetAttribute("Anchor")) + (AnchorStyle) Enum.Parse(typeof(AnchorStyle), contentElement.GetAttribute("Anchor")), + (DockableContentState) Enum.Parse(typeof(DockableContentState), contentElement.GetAttribute("State")) ); - + //contentElement.HasAttribute("State") ? (DockableContentState)Enum.Parse(typeof(DockableContentState), contentElement.GetAttribute("State") ); } } #endregion } } diff --git a/AvalonDock/AvalonDock/DockableTabPanel.cs b/AvalonDock/AvalonDock/DockableTabPanel.cs index 39c757f..8a4b67f 100644 --- a/AvalonDock/AvalonDock/DockableTabPanel.cs +++ b/AvalonDock/AvalonDock/DockableTabPanel.cs @@ -1,110 +1,113 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace AvalonDock { public class DockableTabPanel : PaneTabPanel { protected override Size MeasureOverride(Size availableSize) { double totWidth = 0; //double maxHeight = 0; if (Children.Count == 0) return base.MeasureOverride(availableSize); List<UIElement> childsOrderedByWidth = new List<UIElement>(); - foreach (UIElement child in Children) + foreach (DockableContent child in Children) { + child.Width = double.NaN; + child.Height = double.NaN; + child.Measure(new Size(double.PositiveInfinity, availableSize.Height)); totWidth += child.DesiredSize.Width; childsOrderedByWidth.Add(child); } if (totWidth > availableSize.Width) { childsOrderedByWidth.Sort(delegate(UIElement elem1, UIElement elem2) { return elem2.DesiredSize.Width.CompareTo(elem1.DesiredSize.Width); }); int i = childsOrderedByWidth.Count - 1; double sumWidth = 0; while (childsOrderedByWidth[i].DesiredSize.Width * (i + 1) + sumWidth < availableSize.Width) { sumWidth += childsOrderedByWidth[i].DesiredSize.Width; i--; if (i < 0) break; } double shWidth = (availableSize.Width - sumWidth) / (i + 1); foreach (UIElement child in Children) { if (shWidth < child.DesiredSize.Width) child.Measure(new Size(shWidth, availableSize.Height)); } } return base.MeasureOverride(availableSize); } protected override Size ArrangeOverride(Size finalSize) { double offsetX = 0; foreach (FrameworkElement child in Children) { double childFinalWidth = child.DesiredSize.Width; child.Arrange(new Rect(offsetX, 0, childFinalWidth, finalSize.Height)); offsetX += childFinalWidth; } return base.ArrangeOverride(finalSize); } } } diff --git a/AvalonDock/AvalonDock/DockingManager.cs b/AvalonDock/AvalonDock/DockingManager.cs index 803eac5..9ebfb10 100644 --- a/AvalonDock/AvalonDock/DockingManager.cs +++ b/AvalonDock/AvalonDock/DockingManager.cs @@ -1,972 +1,1000 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Diagnostics; using System.Windows.Interop; using System.ComponentModel; using System.IO; using System.Xml; using System.Linq; using System.Collections; using System.Collections.Specialized; +using System.Collections.ObjectModel; namespace AvalonDock { /// <summary> /// Represents a control which manages a dockable layout for its children /// </summary> public class DockingManager : System.Windows.Controls.ContentControl, IDropSurface, INotifyPropertyChanged, IDisposable { static DockingManager() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml DefaultStyleKeyProperty.OverrideMetadata(typeof(DockingManager), new FrameworkPropertyMetadata(typeof(DockingManager))); } public DockingManager() { DragPaneServices.Register(this); this.Unloaded += new RoutedEventHandler(DockingManager_Unloaded); this.Loaded += new RoutedEventHandler(DockingManager_Loaded); } #region Control lifetime management ~DockingManager() { Dispose(false); } bool _isControlLoaded = false; void DockingManager_Loaded(object sender, RoutedEventArgs e) { foreach (FloatingWindow floatingWindow in _floatingWindows) { floatingWindow.Owner = Window.GetWindow(this); floatingWindow.Show(); } DragPaneServices.Register(this); _isControlLoaded = true; } void DockingManager_Unloaded(object sender, RoutedEventArgs e) { //cleanup pending resources HideAutoHideWindow(); if (_wndInteropWrapper != null) { _wndInteropWrapper.OnWindowPosChanging -= new EventHandler(_wndInteropWrapper_OnWindowPosChanging); _wndInteropWrapper.Dispose(); _wndInteropWrapper = null; } if (_overlayWindow != null) { _overlayWindow.Close(); _overlayWindow = null; } foreach (FloatingWindow floatingWindow in _floatingWindows) floatingWindow.Hide(); //navigator windows are now automatically disposed when //no longer used. In this way we avoid WPF bug: //http://social.msdn.microsoft.com/forums/en/wpf/thread/f3fc5b7e-e035-4821-908c-b6c07e5c7042/ //if (navigatorWindow != null) //{ // navigatorWindow.Close(); // navigatorWindow = null; //} //if (documentNavigatorWindow != null) //{ // documentNavigatorWindow.Close(); // documentNavigatorWindow = null; //} DragPaneServices.Unregister(this); _isControlLoaded = false; } /// <summary> /// Call this function if you want to deallocate external floating windows, that otherwise are closed when main window is closed. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } bool _disposed = false; protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { while (_floatingWindows.Count > 0) { _floatingWindows[0].Owner = null; _floatingWindows[0].Close(); } } _disposed = true; } #endregion Panel _leftAnchorTabPanel; Panel _rightAnchorTabPanel; Panel _topAnchorTabPanel; Panel _bottomAnchorTabPanel; List<Panel> _anchorTabPanels = new List<Panel>(); bool _OnApplyTemplateFlag = false; Panel ReplaceAnchorTabPanel(Panel oldPanel, Panel newPanel) { if (oldPanel == null) { _anchorTabPanels.Add(newPanel); return newPanel; } else { _anchorTabPanels.Remove(oldPanel); while (oldPanel.Children.Count > 0) { UIElement tabToTransfer = oldPanel.Children[0]; oldPanel.Children.RemoveAt(0); newPanel.Children.Add(tabToTransfer); } _anchorTabPanels.Add(newPanel); return newPanel; } } /// <summary> /// Overriden to get a reference to underlying template elements /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); Panel leftPanel = GetTemplateChild("PART_LeftAnchorTabPanel") as Panel; if (leftPanel == null) throw new ArgumentException("PART_LeftAnchorTabPanel template child element not fount!"); Panel rightPanel = GetTemplateChild("PART_RightAnchorTabPanel") as Panel; if (rightPanel == null) throw new ArgumentException("PART_RightAnchorTabPanel template child element not fount!"); Panel topPanel = GetTemplateChild("PART_TopAnchorTabPanel") as Panel; if (topPanel == null) throw new ArgumentException("PART_TopAnchorTabPanel template child element not fount!"); Panel bottomPanel = GetTemplateChild("PART_BottomAnchorTabPanel") as Panel; if (bottomPanel == null) throw new ArgumentException("PART_BottomAnchorTabPanel template child element not fount!"); _leftAnchorTabPanel = ReplaceAnchorTabPanel(_leftAnchorTabPanel, leftPanel); _rightAnchorTabPanel = ReplaceAnchorTabPanel(_rightAnchorTabPanel, rightPanel); _topAnchorTabPanel = ReplaceAnchorTabPanel(_topAnchorTabPanel, topPanel); _bottomAnchorTabPanel = ReplaceAnchorTabPanel(_bottomAnchorTabPanel, bottomPanel); _OnApplyTemplateFlag = true; } #region Access to contents and pane ManagedContent _activeDocument = null; /// <summary> /// Get or set the active document /// </summary> /// <remarks>The active document not neessary receive keyboard focus. To set keyboard focus on a content see <see cref="ActiveContent"/></remarks> public ManagedContent ActiveDocument { get { return _activeDocument; } set { //Debug.WriteLine(string.Format("SetActiveDocument to '{0}'", value != null ? value.Name : "null")); if (_activeDocument != value/* && value.ContainerPane is DocumentPane*/) { if (value != null && (value.FindVisualAncestor<DocumentPane>(false) == null && !(value is DocumentContent)) ) { //value is not contained in a document pane/ documentfloatingwindow so cant be the active document! return; } List<ManagedContent> listOfAllDocuments = FindContents<ManagedContent>(); listOfAllDocuments.ForEach((ManagedContent cnt) => { cnt.IsActiveDocument = cnt == value; }); _activeDocument = value; NotifyPropertyChanged("ActiveDocument"); if (ActiveContent == null) ActiveContent = value; } } } ManagedContent _activeContent = null; /// <summary> /// Get or set the active content /// </summary> /// <remarks>An activated content is automatically selected in its container pane and receive logical as well keyboard focus.</remarks> public ManagedContent ActiveContent { get { return _activeContent; } internal set { //Debug.WriteLine(string.Format("SetActiveContent to '{0}'", value != null ? value.Name : "null")); ActiveDocument = value; if (_activeContent != value) { List<ManagedContent> listOfAllContents = FindContents<ManagedContent>(); listOfAllContents.ForEach((ManagedContent cnt) => { cnt.IsActiveContent = (value == cnt); }); _floatingWindows.ForEach((DockableFloatingWindow fw) => { foreach (DockableContent cnt in fw.HostedPane.Items) { cnt.IsActiveContent = (value == cnt); } }); if (_flyoutWindow != null) { foreach (DockableContent cnt in _flyoutWindow.ReferencedPane.Items) { cnt.IsActiveContent = (value == cnt); } } _activeContent = value; NotifyPropertyChanged("ActiveContent"); } } } /// <summary> /// Gets the active dockable content /// </summary> /// <remarks>If no dockbale content us active at the moment returns null.</remarks> public DockableContent ActiveDockableContent { get { IInputElement focusedElement = FocusManager.GetFocusedElement(this); return focusedElement as DockableContent; } } /// <summary> /// Gets an array of all dockable contents currenty managed /// </summary> public DockableContent[] DockableContents { get { List<DockableContent> contents = FindContents<DockableContent>(); //FindContents already returns contents from FloatingWindows (sg #68987) //foreach (FloatingWindow flWindow in _floatingWindows) //{ // foreach (DockableContent content in flWindow.HostedPane.Items) // contents.Add(content); //} foreach (DockableContent content in _hiddenContents) contents.Add(content); return contents.ToArray(); } } /// <summary> /// Gets an array of all document contents /// </summary> public DocumentContent[] Documents { get { return FindContents<DocumentContent>().ToArray<DocumentContent>(); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Bindable(true)] public IEnumerable DocumentsSource { get { return (IEnumerable)GetValue(DocumentsSourceProperty); } set { SetValue(DocumentsSourceProperty, value); } } // Using a DependencyProperty as the backing store for DocumentsSource. This enables animation, styling, binding, etc... public static readonly DependencyProperty DocumentsSourceProperty = DependencyProperty.Register("DocumentsSource", typeof(IEnumerable), typeof(DockingManager), new UIPropertyMetadata(null, new PropertyChangedCallback((s, e) => ((DockingManager)s).OnDocumentsSourceChanged(e.OldValue as IEnumerable, e.NewValue as IEnumerable)))); void OnDocumentsSourceChanged(IEnumerable oldSource, IEnumerable newSource) { if (oldSource != null) { INotifyCollectionChanged oldSourceNotityIntf = oldSource as INotifyCollectionChanged; if (oldSourceNotityIntf != null) oldSourceNotityIntf.CollectionChanged -= new NotifyCollectionChangedEventHandler(DocumentsSourceCollectionChanged); } if (newSource != null) { INotifyCollectionChanged newSourceNotityIntf = newSource as INotifyCollectionChanged; if (newSourceNotityIntf != null) newSourceNotityIntf.CollectionChanged += new NotifyCollectionChangedEventHandler(DocumentsSourceCollectionChanged); } } void DocumentsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { - if (e.Action == NotifyCollectionChangedAction.Reset) - { - DocumentContent[] docs = this.Documents; - - foreach (DocumentContent doc in docs) - doc.Close(); - } + if (e.Action == NotifyCollectionChangedAction.Reset) + { + DocumentContent[] docs = this.Documents; + ObservableCollection<DocumentContent> documentsToClose = new ObservableCollection<DocumentContent>(); + + foreach (DocumentContent doc in docs) + { + if (doc.Parent is DocumentPane) + { + if ((doc.Parent as DocumentPane).IsMainDocumentPane == false) + { + documentsToClose.Add(doc); + } + } + } + + foreach (DocumentContent doc in documentsToClose) + { + doc.InternalClose(); + } + + foreach (DocumentContent doc in docs) + doc.InternalClose(); + } if (MainDocumentPane == null) return; if (e.Action == NotifyCollectionChangedAction.Remove || e.Action == NotifyCollectionChangedAction.Replace) { foreach (object newDoc in e.OldItems) { if (newDoc is DocumentContent) (newDoc as DocumentContent).InternalClose(); else if (newDoc is FrameworkElement) { DocumentContent docContainer = ((FrameworkElement)newDoc).Parent as DocumentContent; if (docContainer != null) docContainer.InternalClose(); } } } if (e.Action == NotifyCollectionChangedAction.Add || e.Action == NotifyCollectionChangedAction.Replace) { foreach (object newDoc in e.NewItems) { if (newDoc is DocumentContent) MainDocumentPane.Items.Add(newDoc); else if (newDoc is FrameworkElement) //limit objects to be at least framework elements { DocumentContent docContainer = new DocumentContent(); docContainer.Content = newDoc; MainDocumentPane.Items.Add(docContainer); } } } } /// <summary> /// Returns the main document pane /// </summary> /// <param name="parentPanel"></param> /// <returns></returns> internal static DocumentPane GetMainDocumentPane(ResizingPanel parentPanel) { foreach (UIElement child in parentPanel.Children) { if (child is DocumentPane) return child as DocumentPane; + //if (child is DockablePane) + //{ + // DocumentPane doc = new DocumentPane(); + // DockablePane dockablePane = child as DockablePane; + // while (dockablePane.Items.Count > 0) + // { + // doc.Items.Add((dockablePane.Items[0] as DockableContent).DetachFromContainerPane()); + // } + // return doc; + //} if (child is ResizingPanel) { DocumentPane foundDocPane = GetMainDocumentPane(child as ResizingPanel); if (foundDocPane != null) return foundDocPane; } } return null; } internal static bool IsPanelContainingDocumentPane(ResizingPanel parentPanel) { foreach (UIElement child in parentPanel.Children) { if (child is DocumentPane) return true; if (child is ResizingPanel) { bool foundDocPane = IsPanelContainingDocumentPane(child as ResizingPanel); if (foundDocPane) return foundDocPane; } } return false; } internal void EnsurePanePositionIsValid(DocumentPane pane) { if (pane == MainDocumentPane) return; //A document pane must be at maindocument pane level or deeper if (MainDocumentPane.Parent == this) { throw new InvalidOperationException("A document pane can't be positioned at this level!"); } } bool? FindPaneInPanel(ResizingPanel panel, Pane paneToFind) { foreach (UIElement child in panel.Children) { if (child == paneToFind) return true; else if (child is DockablePane) return null; else if (child is ResizingPanel) { bool? found = FindPaneInPanel(child as ResizingPanel, paneToFind); if (found.HasValue && found.Value) return true; } } return false; } DocumentPane _mainDocumentPane; /// <summary> /// Gets the main <see cref="DocumentPane"/> that can be used to add new document /// </summary> public DocumentPane MainDocumentPane { get { return _mainDocumentPane; } internal set { if (_mainDocumentPane == null) { _mainDocumentPane = value; if (DocumentsSource != null) { foreach (object newDoc in DocumentsSource) { if (newDoc is DocumentContent) MainDocumentPane.Items.Add(newDoc); else if (newDoc is FrameworkElement) //limit objects to be at least framework elements { DocumentContent docContainer = new DocumentContent(); docContainer.Content = newDoc; MainDocumentPane.Items.Add(docContainer); } } } } else { _mainDocumentPane = value; } } } internal List<T> FindContents<T>() where T : ManagedContent { List<T> resList = new List<T>(); if (Content is Pane) { foreach (ManagedContent c in ((Pane)Content).Items) { if (c is T) { resList.Add((T)c); } } } else if (Content is ResizingPanel) { FindContents<T>(resList, Content as ResizingPanel); } foreach (FloatingWindow flWindow in _floatingWindows) { foreach (ManagedContent c in flWindow.HostedPane.Items) { if (c is T) resList.Add(c as T); } } if (_flyoutWindow != null && _flyoutWindow.ReferencedPane != null) { foreach (ManagedContent c in _flyoutWindow.ReferencedPane.Items) { if (c is T) resList.Add(c as T); } } return resList; } void FindContents<T>(List<T> listOfFoundContents, ResizingPanel parentPanel) where T : ManagedContent { foreach (UIElement child in parentPanel.Children) { if (child is Pane) { foreach (ManagedContent c in ((Pane)child).Items) { if (c is T) { listOfFoundContents.Add((T)c); } } } else if (child is ResizingPanel) { FindContents<T>(listOfFoundContents, child as ResizingPanel); } } } #endregion #region Floating windows management List<DockableFloatingWindow> _floatingWindows = new List<DockableFloatingWindow>(); public DockableFloatingWindow[] FloatingWindows { get { if (_floatingWindows == null || _floatingWindows.Count == 0) return new DockableFloatingWindow[0]; return _floatingWindows.ToArray(); } } internal void RegisterFloatingWindow(DockableFloatingWindow floatingWindow) { if (_floatingWindows != null) { floatingWindow.FlowDirection = this.FlowDirection; _floatingWindows.Add(floatingWindow); } } internal void UnregisterFloatingWindow(DockableFloatingWindow floatingWindow) { if (_floatingWindows != null) _floatingWindows.Remove(floatingWindow); } protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); this.CommandBindings.Clear(); this.CommandBindings.Add(new CommandBinding(ShowNavigatorWindowCommand, OnExecuteCommand, OnCanExecuteCommand)); this.CommandBindings.Add(new CommandBinding(ShowDocumentNavigatorWindowCommand, OnExecuteCommand, OnCanExecuteCommand)); } protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) { if (e.Property == FlowDirectionProperty) { _floatingWindows.ForEach((DockableFloatingWindow fl) => { fl.FlowDirection = FlowDirection; }); if (_flyoutWindow != null) { _flyoutWindow.FlowDirection = FlowDirection; } } base.OnPropertyChanged(e); } #endregion #region Commands private static object syncRoot = new object(); private static RoutedUICommand showNavigatorCommand = null; /// <summary> /// Get the command to show navigator window /// </summary> public static RoutedUICommand ShowNavigatorWindowCommand { get { lock (syncRoot) { if (null == showNavigatorCommand) { showNavigatorCommand = new RoutedUICommand("S_how navigator window", "Navigator", typeof(DockingManager)); showNavigatorCommand.InputGestures.Add(new KeyGesture(Key.Tab, ModifierKeys.Control)); } } return showNavigatorCommand; } } NavigatorWindow navigatorWindow = null; void ShowNavigatorWindow() { HideNavigatorWindow(); if (navigatorWindow == null) { navigatorWindow = new NavigatorWindow(this); navigatorWindow.Owner = Window.GetWindow(this); } Point locDockingManager = this.PointToScreenDPI(new Point()); navigatorWindow.Left = locDockingManager.X; navigatorWindow.Top = locDockingManager.Y; navigatorWindow.Width = this.ActualWidth; navigatorWindow.Height = this.ActualHeight; navigatorWindow.Show(); navigatorWindow.Focus(); } void HideNavigatorWindow() { if (navigatorWindow != null) { navigatorWindow.Close(); navigatorWindow = null; } } void OnExecuteCommand(object sender, ExecutedRoutedEventArgs e) { if (e.Command == ShowNavigatorWindowCommand && ((Keyboard.Modifiers & ModifierKeys.Control)>0) ) { ShowNavigatorWindow(); e.Handled = true; } else if (e.Command == ShowDocumentNavigatorWindowCommand && ((Keyboard.Modifiers & ModifierKeys.Shift) > 0)) { ShowDocumentNavigatorWindow(); e.Handled = true; } } void OnCanExecuteCommand(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } private static RoutedUICommand showDocumentNavigatorCommand = null; /// <summary> /// Get the command to show document navigator window /// </summary> public static RoutedUICommand ShowDocumentNavigatorWindowCommand { get { lock (syncRoot) { if (null == showDocumentNavigatorCommand) { showDocumentNavigatorCommand = new RoutedUICommand("S_how document navigator window", "DocumentNavigator", typeof(DockingManager)); showDocumentNavigatorCommand.InputGestures.Add(new KeyGesture(Key.Tab, ModifierKeys.Shift)); } } return showDocumentNavigatorCommand; } } DocumentNavigatorWindow documentNavigatorWindow = null; void ShowDocumentNavigatorWindow() { HideDocumentNavigatorWindow(); //if (documentNavigatorWindow == null) { documentNavigatorWindow = new DocumentNavigatorWindow(this); documentNavigatorWindow.Owner = Window.GetWindow(this); } if (MainDocumentPane == null) return; Point locMainDocumentPane = MainDocumentPane.PointToScreenDPI(new Point()); documentNavigatorWindow.Left = locMainDocumentPane.X; documentNavigatorWindow.Top = locMainDocumentPane.Y; documentNavigatorWindow.Width = MainDocumentPane.ActualWidth; documentNavigatorWindow.Height = MainDocumentPane.ActualHeight; documentNavigatorWindow.Show(); documentNavigatorWindow.Focus(); } void HideDocumentNavigatorWindow() { //if (documentNavigatorWindow != null) //{ // documentNavigatorWindow.Hide(); // //don't close this window to be more responsive // documentNavigatorWindow.Close(); // documentNavigatorWindow = null; //} } #endregion #region DockablePane operations /// <summary> /// Anchor a dockable pane to a border /// </summary> /// <param name="paneToAnchor"></param> /// <param name="anchor"></param> public void Anchor(Pane paneToAnchor, AnchorStyle anchor) { //remove the pane from its original children collection FrameworkElement parentElement = paneToAnchor.Parent as FrameworkElement; if (anchor == AnchorStyle.None) anchor = AnchorStyle.Right; //Change anchor border according to FlowDirection if (FlowDirection == FlowDirection.RightToLeft) { if (anchor == AnchorStyle.Right) anchor = AnchorStyle.Left; else if (anchor == AnchorStyle.Left) anchor = AnchorStyle.Right; } //parentElement should be a DockingManager or a ResizingPanel if (parentElement is ContentControl) { ((ContentControl)parentElement).Content = null; } //and insert in the top level panel if exist ResizingPanel toplevelPanel = Content as ResizingPanel; Orientation requestedOrientation = (anchor == AnchorStyle.Bottom || anchor == AnchorStyle.Top) ? Orientation.Vertical : Orientation.Horizontal; //if toplevel panel contains only one child then just override the orientation //as requested if (toplevelPanel != null && toplevelPanel.Children.Count == 1) toplevelPanel.Orientation = requestedOrientation; if (toplevelPanel == null || toplevelPanel.Orientation != requestedOrientation) { //if toplevel panel doesn't exist or it has not the correct orientation //we have to create a new one and set it as content of docking manager toplevelPanel = new ResizingPanel(); toplevelPanel.Orientation = requestedOrientation; FrameworkElement contentElement = Content as FrameworkElement; Content = toplevelPanel; if (anchor == AnchorStyle.Left || anchor == AnchorStyle.Top) { toplevelPanel.Children.Add(paneToAnchor); toplevelPanel.InsertChildRelativeTo(contentElement, paneToAnchor, true); } else { toplevelPanel.Children.Add(paneToAnchor); toplevelPanel.InsertChildRelativeTo(contentElement, paneToAnchor, false); } } else { //here we have a docking manager content with the right orientation //so we have only to insert new child at correct position if (anchor == AnchorStyle.Left || anchor == AnchorStyle.Top) { //add new child before first one (prepend) toplevelPanel.InsertChildRelativeTo(paneToAnchor, toplevelPanel.Children[0] as FrameworkElement, false); } else { //add new child after last one (append) toplevelPanel.InsertChildRelativeTo(paneToAnchor, toplevelPanel.Children[toplevelPanel.Children.Count - 1] as FrameworkElement, true); } } //Refresh anchor style DockablePane paneToAnchorAsDockablePane = paneToAnchor as DockablePane; if (paneToAnchorAsDockablePane != null) { paneToAnchorAsDockablePane.Anchor = anchor; } if (anchor == AnchorStyle.Left || anchor == AnchorStyle.Right) { double w = Math.Min( ActualWidth / 2.0, ResizingPanel.GetEffectiveSize(paneToAnchor).Width); ResizingPanel.SetResizeWidth(paneToAnchor, new GridLength(w, GridUnitType.Pixel)); ResizingPanel.SetResizeHeight(paneToAnchor, new GridLength(1.0, GridUnitType.Star)); } else { double h = Math.Min( ActualHeight / 2.0, ResizingPanel.GetEffectiveSize(paneToAnchor).Height); ResizingPanel.SetResizeWidth(paneToAnchor, new GridLength(1.0, GridUnitType.Star)); ResizingPanel.SetResizeHeight(paneToAnchor, new GridLength(h, GridUnitType.Pixel)); } //refresh contents state foreach (ManagedContent content in paneToAnchor.Items) { if (content is DockableContent) { ((DockableContent)content).SetStateToDock(); } } paneToAnchor.Focus(); } /// <summary> /// Anchor a dockable pane (<see cref="DockablePane"/>) to a border of a docked pane /// </summary> /// <param name="paneToAnchor">Pane to anchor</param> /// <param name="relativePane">Pane relative</param> /// <param name="anchor"></param> public void Anchor(Pane paneToAnchor, Pane relativePane, AnchorStyle anchor) { if (anchor == AnchorStyle.None) anchor = AnchorStyle.Right; //Change anchor border according to FlowDirection if (FlowDirection == FlowDirection.RightToLeft) { if (anchor == AnchorStyle.Right) anchor = AnchorStyle.Left; else if (anchor == AnchorStyle.Left) anchor = AnchorStyle.Right; } if (paneToAnchor is DockablePane && relativePane is DockablePane) Anchor(paneToAnchor as DockablePane, relativePane as DockablePane, anchor); else if (paneToAnchor is DockablePane && relativePane is DocumentPane) @@ -1198,1978 +1226,2012 @@ namespace AvalonDock relativePaneContainer.Children.Remove(relativePane); relativePaneContainer.Children.Insert(indexofRelativePane, newPanel); //now we have a panel correctly placed in the tree newPanel.Children.Add(relativePane); //use InsertChildRelativeTo function to add a resizingsplitter between //the two children newPanel.InsertChildRelativeTo( paneToAnchor, relativePane, anchor == AnchorStyle.Right || anchor == AnchorStyle.Bottom); relativePaneContainer = newPanel; } else { if (anchor == AnchorStyle.Left || anchor == AnchorStyle.Top) { //add new child before first (prepend) relativePaneContainer.InsertChildRelativeTo(paneToAnchor, relativePane, false); } else { //add new child after last (append) relativePaneContainer.InsertChildRelativeTo(paneToAnchor, relativePane, true); } } } #endregion paneToAnchor.Focus(); (paneToAnchor.SelectedItem as ManagedContent).SetAsActive(); if (paneToAnchor.SelectedItem is DocumentContent) ActiveDocument = paneToAnchor.SelectedItem as DocumentContent; } /// <summary> /// Anchor a dockable pane (<see cref="DockablePane"/>) to a border of an other dockable pane /// </summary> /// <param name="paneToAnchor">Pane to anchor</param> /// <param name="relativePane">Pane relative</param> /// <param name="anchor"></param> public void Anchor(DockablePane paneToAnchor, DockablePane relativePane, AnchorStyle anchor) { if (anchor == AnchorStyle.None) anchor = AnchorStyle.Right; //get a refernce to the resizingpanel container of relativePane ResizingPanel relativePaneContainer = LogicalTreeHelper.GetParent(relativePane) as ResizingPanel; Orientation requestedOrientation = (anchor == AnchorStyle.Bottom || anchor == AnchorStyle.Top) ? Orientation.Vertical : Orientation.Horizontal; if (relativePaneContainer == null) { Debug.Assert(relativePane.Parent == this); relativePaneContainer = new ResizingPanel(); relativePaneContainer.Orientation = requestedOrientation; this.Content = relativePaneContainer; relativePaneContainer.Children.Add(relativePane); } Debug.Assert(relativePaneContainer != null, "By now we can't have a pane without a resizing panel containing it"); #region Create and setup container panel if (relativePaneContainer != null) { //check if orientation is right if (relativePaneContainer.Orientation != requestedOrientation) { //if the existing panel is not oriented as we want //create a new one ResizingPanel newPanel = new ResizingPanel(); newPanel.Orientation = requestedOrientation; if (newPanel.Orientation == Orientation.Horizontal) ResizingPanel.SetResizeHeight(newPanel, ResizingPanel.GetResizeHeight(relativePane)); else ResizingPanel.SetResizeWidth(newPanel, ResizingPanel.GetResizeWidth(relativePane)); //replace relative pane in its' container panel //with this new panel int indexofRelativePane = relativePaneContainer.Children.IndexOf(relativePane); relativePaneContainer.Children.Remove(relativePane); relativePaneContainer.Children.Insert(indexofRelativePane, newPanel); //now we have a panel correctly placed in the tree newPanel.Children.Add(relativePane); newPanel.InsertChildRelativeTo( paneToAnchor, relativePane, anchor == AnchorStyle.Right || anchor == AnchorStyle.Bottom); relativePaneContainer = newPanel; } else { if (anchor == AnchorStyle.Left || anchor == AnchorStyle.Top) { //add new child before first (prepend) relativePaneContainer.InsertChildRelativeTo(paneToAnchor, relativePane, false); } else { //add new child after last (append) relativePaneContainer.InsertChildRelativeTo(paneToAnchor, relativePane, true); } } } #endregion //than set the new anchor style for the pane paneToAnchor.Anchor = relativePane.Anchor; if (anchor == AnchorStyle.Left || anchor == AnchorStyle.Right) { double w = Math.Min( ResizingPanel.GetEffectiveSize(relativePane).Width / 2.0, ResizingPanel.GetEffectiveSize(paneToAnchor).Width); ResizingPanel.SetResizeWidth(paneToAnchor, new GridLength(w, GridUnitType.Pixel)); ResizingPanel.SetResizeHeight(paneToAnchor, new GridLength(1.0, GridUnitType.Star)); } else { double h = Math.Min( ResizingPanel.GetEffectiveSize(relativePane).Height / 2.0, ResizingPanel.GetEffectiveSize(paneToAnchor).Height); ResizingPanel.SetResizeWidth(paneToAnchor, new GridLength(1.0, GridUnitType.Star)); ResizingPanel.SetResizeHeight(paneToAnchor, new GridLength(h, GridUnitType.Pixel)); } //refresh contents state foreach (DockableContent draggedContent in paneToAnchor.Items) { draggedContent.SetStateToDock(); } if (relativePaneContainer != null) relativePaneContainer.AdjustPanelSizes(); paneToAnchor.Focus(); } public void DropInto(Pane paneDragged, Pane paneToDropInto) { if (paneDragged is DockablePane && paneToDropInto is DockablePane) DropInto(paneDragged as DockablePane, paneToDropInto as DockablePane); else if (paneDragged is DockablePane && paneToDropInto is DocumentPane) DropInto(paneDragged as DockablePane, paneToDropInto as DocumentPane); else if (paneDragged is DocumentPane && paneToDropInto is DocumentPane) DropInto(paneDragged as DocumentPane, paneToDropInto as DocumentPane); else Debug.Assert(false); } public void DropInto(DocumentPane paneDragged, DocumentPane paneToDropInto) { //transfer tha contents of dragged pane (conatined in a FloatingWindow) //to the pane which user select ManagedContent contentToFocus = null; while (paneDragged.Items.Count > 0) { ManagedContent contentToTransfer = paneDragged.RemoveContent(0); paneToDropInto.Items.Insert(0, contentToTransfer); contentToFocus = contentToTransfer; } paneToDropInto.SelectedIndex = 0; paneToDropInto.Focus(); if (contentToFocus != null) contentToFocus.SetAsActive(); } public void DropInto(DockablePane paneDragged, DocumentPane paneToDropInto) { if (paneToDropInto != MainDocumentPane) paneToDropInto = MainDocumentPane; //transfer contents of dragged pane (contained in a FloatingWindow) //to the pane which user select, taking care of setting contents state //to Dock (using Dock() method of class DockablePane). while (paneDragged.Items.Count > 0) { ManagedContent contentToTransfer = paneDragged.RemoveContent(0); paneToDropInto.Items.Add(contentToTransfer); DockableContent dockContentToTransfer = contentToTransfer as DockableContent; if (dockContentToTransfer != null) dockContentToTransfer.SetStateToDocument(); } paneToDropInto.SelectedIndex = paneToDropInto.Items.Count - 1; paneToDropInto.Focus(); } public void DropInto(DockablePane paneDragged, DockablePane paneToDropInto) { //transfer tha contents of dragged pane (conatined in a FloatingWindow) //to the pane which user select, taking care of setting contents state //to Dock (using Dock() method of class DockablePane). while (paneDragged.Items.Count > 0) { ManagedContent contentToTransfer = paneDragged.RemoveContent(0); paneToDropInto.Items.Add(contentToTransfer); DockableContent dockContentToTransfer = contentToTransfer as DockableContent; if (dockContentToTransfer != null) dockContentToTransfer.SetStateToDock(); } paneToDropInto.SelectedIndex = paneToDropInto.Items.Count - 1; paneToDropInto.Focus(); } bool RemoveContentFromTabGroup(DockableContent contentToRemove) { foreach (Panel anchorTabPanel in _anchorTabPanels) { foreach (DockablePaneAnchorTabGroup group in anchorTabPanel.Children) { foreach (DockablePaneAnchorTab tab in group.Children) { if (tab.ReferencedContent == contentToRemove) { group.Children.Remove(tab); if (group.Children.Count == 0) anchorTabPanel.Children.Remove(group); return true; } } } } return false; } /// <summary> /// Remove a pane from border tab groups /// </summary> /// <param name="pane">Pane to remove</param> /// <returns>True if pane was removed, false otherwise</returns> bool RemovePaneFromTabGroups(DockablePane paneToRemove) { foreach (Panel anchorTabPanel in _anchorTabPanels) { foreach (DockablePaneAnchorTabGroup group in anchorTabPanel.Children) { if (group.ReferencedPane == paneToRemove) { //foreach (DockablePaneAnchorTab tab in group.Children) //{ // tab.ReferencedContent.Icon = tab.Icon; // tab.Icon = null; //} anchorTabPanel.Children.Remove(group); return true; } } } return false; } /// <summary> /// Autohides/redock a dockable pane /// </summary> /// <param name="pane">Pane to auto hide/redock</param> public void ToggleAutoHide(DockablePane pane) { if (!_OnApplyTemplateFlag) { Debug.WriteLine("Layout has been restored before creating DockingManager object: force WPF to apply the template..."); ApplyTemplate(); } //if pane is in auto hide state then is found //referenced by a DockablePaneAnchorTabGroup //if so redock it in its original position if (RemovePaneFromTabGroups(pane)) { #region Pane is present in tab anchor panels DockableContent selectedContent = _flyoutWindow != null && _flyoutWindow.ReferencedPane != null && _flyoutWindow.ReferencedPane.Items.Count > 0 ? _flyoutWindow.ReferencedPane.Items[0] as DockableContent : pane.Items[0] as DockableContent; HideAutoHideWindow(); ResizingPanel parentPanel = pane.Parent as ResizingPanel; if (parentPanel != null && parentPanel.Children.Count >= 3) { parentPanel.AdjustPanelSizes(); } //reset content state to docked foreach (DockableContent content in pane.Items) { content.SetStateToDock(); } pane.Focus(); pane.SelectedItem = selectedContent; ActiveContent = selectedContent; #endregion } else { #region Pane is not auto hidden //Create e new group DockablePaneAnchorTabGroup group = new DockablePaneAnchorTabGroup(); //associate it to the pane group.ReferencedPane = pane; DockableContent selectedContent = pane.SelectedItem as DockableContent; //add contents to it foreach (DockableContent content in pane.Items) { DockablePaneAnchorTab tab = new DockablePaneAnchorTab(); tab.ReferencedContent = content; tab.Anchor = pane.Anchor; tab.Icon = content.Icon; group.Children.Add(tab); content.SetStateToAutoHide(); } //place group under correct anchor tabpanel switch (pane.Anchor) { case AnchorStyle.Left: if (_leftAnchorTabPanel != null) _leftAnchorTabPanel.Children.Add(group); break; case AnchorStyle.Top: if (_topAnchorTabPanel != null) _topAnchorTabPanel.Children.Add(group); break; case AnchorStyle.Right: if (_rightAnchorTabPanel != null) _rightAnchorTabPanel.Children.Add(group); break; case AnchorStyle.Bottom: if (_bottomAnchorTabPanel != null) _bottomAnchorTabPanel.Children.Add(group); break; } #endregion } //refresh arrangements traversing bottom-up visual tree FrameworkElement parentElement = pane.Parent as FrameworkElement; while (parentElement != null) { parentElement.InvalidateMeasure(); parentElement = parentElement.Parent as FrameworkElement; } } #endregion #region Hide/Show contents List<DockableContent> _hiddenContents = new List<DockableContent>(); #if DEBUG internal void CheckHiddenState(DockableContent contentToCheck) { if (contentToCheck.State == DockableContentState.Hidden) Debug.Assert(_hiddenContents.Contains(contentToCheck)); else Debug.Assert(!_hiddenContents.Contains(contentToCheck)); } #endif /// <summary> /// Hide a dockable content removing it from its container <see cref="Pane"/> /// </summary> /// <param name="content">Content to hide</param> /// <remarks>Note that if you simply remove a content from its container without calling this method, the /// layout serializer component can't managed correctly the removed content.</remarks> public void Hide(DockableContent content) { if (content.State == DockableContentState.Hidden) return; if (!content.IsCloseable) return; content.SaveCurrentStateAndPosition(); if (content.State == DockableContentState.AutoHide) { HideAutoHideWindow(); RemoveContentFromTabGroup(content); } if (content.State == DockableContentState.FloatingWindow || content.State == DockableContentState.DockableWindow) { DockableFloatingWindow floatingWindow = Window.GetWindow(content) as DockableFloatingWindow; if (floatingWindow != null && floatingWindow.HostedPane.HasSingleItem) { floatingWindow.Close(); } content.DetachFromContainerPane(); } else { content.DetachFromContainerPane(); } if (content.State != DockableContentState.Hidden) { content.SetStateToHidden(); Debug.Assert(!_hiddenContents.Contains(content)); _hiddenContents.Add(content); } if (ActiveDocument == content) ActiveDocument = null; if (ActiveContent == content) ActiveContent = null; } /// <summary> /// Show or add a document in AvalonDock /// </summary> /// <param name="document">Document to show/add.</param> /// <remarks>If document provided is not present in the <see cref="Documents"/> list, this method inserts it in first position of <see cref="MainDocumentPane.Items"/> collection. /// In both cases select it in the container <see cref="DocumentPane"/>.</remarks> public void Show(DocumentContent document) { bool found = false; foreach (DocumentContent doc in Documents) { if (doc == document) { found = true; break; } } if (!found && MainDocumentPane != null) { if (document.Parent is DocumentPane) { ((DocumentPane)document.Parent).Items.Clear(); } //if (document.Parent != null) //{ // throw new InvalidProgramException( // string.Format("Disconnnect first the document from its logical parent ({0})", // document.Parent.GetType())); //} MainDocumentPane.Items.Insert(0, document); } //DocumentPane docPane = document.ContainerPane as DocumentPane; //if (docPane != null) //{ // docPane.SelectedItem = document; // if (document.Content is IInputElement) // Keyboard.Focus(document.Content as IInputElement); //} document.SetAsActive(); } /// <summary> /// Show a dockable content in its container <see cref="Pane"/> /// </summary> /// <param name="content">Content to show</param> public void Show(DockableContent content) { - Show(content, DockableContentState.Docked); + if (content.SavedStateAndPosition != null) + Show(content, content.SavedStateAndPosition.State); + else + Show(content, DockableContentState.Docked); } /// <summary> /// Show a dockable content in its container with a desidered state /// </summary> /// <param name="content">Content to show</param> /// <param name="desideredState">State desidered</param> public void Show(DockableContent content, DockableContentState desideredState) { Show(content, desideredState, AnchorStyle.None); } /// <summary> /// Show a dockable content in its container with a desidered state /// </summary> /// <param name="content">Content to show</param> /// <param name="desideredState">State desidered</param> /// <param name="desideredAnchor">Border to which anchor the newly created container pane</param> /// <remarks></remarks> public void Show(DockableContent content, DockableContentState desideredState, AnchorStyle desideredAnchor) { #region Dockable content if (desideredState == DockableContentState.Hidden)//??!!show hidden? Hide(content); if (content.State == DockableContentState.AutoHide) { ShowFlyoutWindow(content); } else if (content.State == DockableContentState.Docked || content.State == DockableContentState.Document) { if (content.ContainerPane == null) { //Problem!? try to rescue if (content.State == DockableContentState.Docked) { //find the the pane which the desidered anchor style DockablePane foundPane = this.FindChildDockablePane(desideredAnchor); if (foundPane != null) foundPane.Items.Add(content); else { //if no suitable pane was found create e new one on the fly DockablePane pane = new DockablePane(); pane.Items.Add(content); Anchor(pane, desideredAnchor); } } else { //add to main document pane MainDocumentPane.Items.Add(content); } } if (content.ContainerPane.GetManager() == null) { //disconnect the parent pane from previous panel //((Panel)content.ContainerPane.Parent).Children.Remove(content.ContainerPane); if (content.ContainerPane.Parent != null) { ((Panel)content.ContainerPane.Parent).Children.Remove(content.ContainerPane); } Anchor(content.ContainerPane, desideredAnchor); } if (desideredState == DockableContentState.DockableWindow || desideredState == DockableContentState.FloatingWindow) { DockableFloatingWindow floatingWindow = new DockableFloatingWindow(this, content); floatingWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner; floatingWindow.Owner = Window.GetWindow(this); //if (content.Content != null) //{ // floatingWindow.Width = Math.Min(((FrameworkElement)content.Content).ActualWidth, ResizingPanel.GetResizeWidth(content.ContainerPane)); // floatingWindow.Height = Math.Min(((FrameworkElement)content.Content).ActualHeight, ResizingPanel.GetResizeHeight(content.ContainerPane)); //} //else //{ floatingWindow.Width = 400; floatingWindow.Height = 400; //} RegisterFloatingWindow(floatingWindow); floatingWindow.Show(); } else if (desideredState == DockableContentState.AutoHide) { if (content.ContainerPane != null) content.ContainerPane.SelectedItem = this; //content.FocusContent(); //if (content.Content is IInputElement) // Keyboard.Focus(content.Content as IInputElement); content.SetAsActive(); DockablePane.ToggleAutoHideCommand.Execute(null, content.ContainerPane); } else if (desideredState == DockableContentState.Document) { DocumentPane docPane = MainDocumentPane; if (docPane != null) { docPane.Items.Add(content.DetachFromContainerPane()); docPane.SelectedItem = content; content.SetStateToDocument(); } } else { content.ContainerPane.SelectedItem = content; content.SetAsActive(); DockablePane dockParent = content.ContainerPane as DockablePane; if (content.ActualWidth == 0.0 && ( dockParent.Anchor == AnchorStyle.Left || dockParent.Anchor == AnchorStyle.Right)) { ResizingPanel.SetResizeWidth(dockParent, new GridLength(200)); ResizingPanel.SetEffectiveSize(dockParent, new Size(200, 0.0)); } else if (content.ActualWidth == 0.0 && ( dockParent.Anchor == AnchorStyle.Left || dockParent.Anchor == AnchorStyle.Right)) { ResizingPanel.SetResizeWidth(dockParent, new GridLength(200)); ResizingPanel.SetEffectiveSize(dockParent, new Size(200, 0.0)); } //ActiveContent = content; ////content.FocusContent(); //if (content.Content is IInputElement) // Keyboard.Focus(content.Content as IInputElement); } } else if ( content.State == DockableContentState.DockableWindow || content.State == DockableContentState.FloatingWindow) { FloatingDockablePane containerPane = content.ContainerPane as FloatingDockablePane; if (containerPane != null) { //check if visible on the primary screen if (containerPane.FloatingWindow.Left > System.Windows.SystemParameters.PrimaryScreenWidth) containerPane.FloatingWindow.Left = System.Windows.SystemParameters.PrimaryScreenWidth - containerPane.FloatingWindow.Width; if (containerPane.FloatingWindow.Top > System.Windows.SystemParameters.PrimaryScreenHeight) containerPane.FloatingWindow.Top = System.Windows.SystemParameters.PrimaryScreenHeight - containerPane.FloatingWindow.Height; containerPane.FloatingWindow.Activate(); } } else if (content.State == DockableContentState.Document) { if (content.ContainerPane != null) content.ContainerPane.SelectedItem = this; //content.FocusContent(); //if (content.Content is IInputElement) // Keyboard.Focus(content.Content as IInputElement); content.SetAsActive(); } else if (content.State == DockableContentState.Hidden) { Debug.Assert(_hiddenContents.Contains(content)); _hiddenContents.Remove(content); if (desideredState == DockableContentState.Docked || desideredState == DockableContentState.AutoHide) { if (content.SavedStateAndPosition != null && content.SavedStateAndPosition.ContainerPane != null && content.SavedStateAndPosition.ChildIndex >= 0 && content.SavedStateAndPosition.ContainerPane.GetManager() == this && desideredState == DockableContentState.Docked) { //ok previous container pane is here.. Pane prevPane = content.SavedStateAndPosition.ContainerPane; if (content.SavedStateAndPosition.ChildIndex < prevPane.Items.Count) { prevPane.Items.Insert(content.SavedStateAndPosition.ChildIndex, content); } else { prevPane.Items.Add(content); } prevPane.SelectedItem = content; content.SetStateToDock(); } else { DockablePane newHostpane = new DockablePane(); newHostpane.Items.Add(content); if (desideredAnchor == AnchorStyle.None && content.SavedStateAndPosition != null && content.SavedStateAndPosition.Anchor != AnchorStyle.None) desideredAnchor = content.SavedStateAndPosition.Anchor; if (desideredAnchor == AnchorStyle.None) desideredAnchor = AnchorStyle.Right; if (desideredAnchor == AnchorStyle.Left || desideredAnchor == AnchorStyle.Right) { double w = 200; if (content.SavedStateAndPosition != null && !double.IsInfinity(content.SavedStateAndPosition.Width) && !double.IsNaN(content.SavedStateAndPosition.Width)) w = content.SavedStateAndPosition.Width; ResizingPanel.SetResizeWidth(newHostpane, new GridLength(w)); ResizingPanel.SetEffectiveSize(newHostpane, new Size(w, 0.0)); } else { double h = 200; if (content.SavedStateAndPosition != null && !double.IsInfinity(content.SavedStateAndPosition.Height) && !double.IsNaN(content.SavedStateAndPosition.Height)) h = content.SavedStateAndPosition.Height; ResizingPanel.SetResizeHeight(newHostpane, new GridLength(h)); ResizingPanel.SetEffectiveSize(newHostpane, new Size(0.0, h)); } Anchor(newHostpane, desideredAnchor); if (desideredState == DockableContentState.AutoHide) { DockablePane.ToggleAutoHideCommand.Execute(null, newHostpane); } } ActiveContent = content; } else if (desideredState == DockableContentState.DockableWindow || desideredState == DockableContentState.FloatingWindow) { - DockablePane newHostpane = new DockablePane(); - newHostpane.Items.Add(content); - content.SetStateToDock(); - - //ResizingPanel.SetResizeWidth(newHostpane, 200); - //ResizingPanel.SetResizeWidth(newHostpane, 500); - - DockableFloatingWindow floatingWindow = new DockableFloatingWindow(this, newHostpane); - floatingWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner; - floatingWindow.Width = 200; - floatingWindow.Height = 500; - floatingWindow.Owner = Window.GetWindow(this); - RegisterFloatingWindow(floatingWindow); - floatingWindow.Show(); + DockablePane newHostpane = null; + FloatingDockablePane prevHostpane = null; + if (content.SavedStateAndPosition != null && content.SavedStateAndPosition.ContainerPane != null && content.SavedStateAndPosition.ContainerPane is FloatingDockablePane) + { + prevHostpane = content.SavedStateAndPosition.ContainerPane as FloatingDockablePane; + if (!prevHostpane.Items.Contains(content)) + prevHostpane.Items.Add(content); + } + else + { + newHostpane = new DockablePane(); + newHostpane.Items.Add(content); + } + + content.SetStateToDock(); + + if (prevHostpane != null) + { + DockableFloatingWindow floatingWindow = new DockableFloatingWindow(this, content); + floatingWindow.WindowStartupLocation = WindowStartupLocation.Manual; + floatingWindow.Top = prevHostpane.FloatingWindow.Top; + floatingWindow.Left = prevHostpane.FloatingWindow.Left; + floatingWindow.Width = prevHostpane.FloatingWindow.Width; + floatingWindow.Height = prevHostpane.FloatingWindow.Height; + floatingWindow.Owner = Window.GetWindow(this); + RegisterFloatingWindow(floatingWindow); + floatingWindow.Show(); + } + else if (newHostpane != null) + { + DockableFloatingWindow floatingWindow = new DockableFloatingWindow(this, newHostpane); + floatingWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen; + floatingWindow.Width = 200; + floatingWindow.Height = 500; + floatingWindow.Owner = Window.GetWindow(this); + RegisterFloatingWindow(floatingWindow); + floatingWindow.Show(); + } } else if (desideredState == DockableContentState.Document) { DocumentPane docPane = MainDocumentPane; if (docPane != null) { docPane.Items.Add(content); docPane.SelectedItem = content; content.SetStateToDocument(); } } } #endregion #if DEBUG CheckHiddenState(content); #endif } #endregion #region Anchor Style Update routines protected override Size ArrangeOverride(Size arrangeBounds) { //at the moment this is the easy way to get anchor properties always updated if (this.Content as ResizingPanel != null) UpdateAnchorStyle(); return base.ArrangeOverride(arrangeBounds); } internal void UpdateAnchorStyle() { ResizingPanel mainPanel = this.Content as ResizingPanel; Debug.Assert(mainPanel != null); UpdateAnchorStyle(mainPanel); } /// <summary> /// Update the <see cref="DockablePane.Anchor"/> property relative to the <see cref="DocumentContent"/> object /// </summary> /// <param name="panel"></param> /// <returns></returns> /// <remarks>Traverse the logical tree starting from root <see cref="ResizingPanel"/> and set property <see cref="DockablePane.Anchor"/> of dockable pane found.</remarks> void UpdateAnchorStyle(ResizingPanel panel) { AnchorStyle currentAnchor = panel.Orientation == Orientation.Horizontal ? AnchorStyle.Left : AnchorStyle.Top; bool foundDocumentContent = false; foreach (FrameworkElement child in panel.Children) { if (child is ResizingPanel) { if (!foundDocumentContent && GetMainDocumentPane(child as ResizingPanel) != null) { foundDocumentContent = true; currentAnchor = panel.Orientation == Orientation.Horizontal ? AnchorStyle.Right : AnchorStyle.Bottom; UpdateAnchorStyle(child as ResizingPanel); } else ForceAnchorStyle(child as ResizingPanel, currentAnchor); } else if (child is DocumentPane) { foundDocumentContent = true; currentAnchor = panel.Orientation == Orientation.Horizontal ? AnchorStyle.Right : AnchorStyle.Bottom; } else if (child is DockablePane) { (child as DockablePane).Anchor = currentAnchor; } } } /// <summary> /// Called by <see cref="UpdateAnchorStyle"/> whene a <see cref="DocumentContent"/> object has been found /// </summary> /// <param name="panel"></param> /// <param name="forcedAnchor"></param> void ForceAnchorStyle(ResizingPanel panel, AnchorStyle forcedAnchor) { foreach (FrameworkElement child in panel.Children) { if (child is ResizingPanel) { ForceAnchorStyle((child as ResizingPanel), forcedAnchor); } else if ((child is DockablePane)) { ((DockablePane)child).Anchor = forcedAnchor; } } } #endregion #region Flyout window FlyoutPaneWindow _flyoutWindow = null; WindowInteropWrapper _wndInteropWrapper = null; void HideAutoHideWindow() { if (_flyoutWindow != null) { _flyoutWindow.Height = 0.0; _flyoutWindow.Width = 0.0; _flyoutWindow.Close(); _flyoutWindow = null; } } internal void ShowFlyoutWindow(DockableContent content) { //check if parent window is Active Window parentWindow = Window.GetWindow(this); if (parentWindow == null) return; if (!parentWindow.IsActive && (_flyoutWindow == null || !_flyoutWindow.IsActive)) return; //check if content is already visible in a flyout window if (_flyoutWindow != null && _flyoutWindow.ReferencedPane.Items.Contains(content)) return; //hide previous create window HideAutoHideWindow(); //select this content in the referenced pane content.ContainerPane.SelectedItem = content; if (_wndInteropWrapper == null) { _wndInteropWrapper = new WindowInteropWrapper(); _wndInteropWrapper.OnWindowPosChanging+=new EventHandler(_wndInteropWrapper_OnWindowPosChanging); } _wndInteropWrapper.AttachedObject = parentWindow; //create e new window _flyoutWindow = new FlyoutPaneWindow(this, content); _flyoutWindow.Owner = parentWindow; _flyoutWindow.FlowDirection = this.FlowDirection; UpdateFlyoutWindowPosition(true); _flyoutWindow.Closing += new System.ComponentModel.CancelEventHandler(_flyoutWindow_Closing); _flyoutWindow.Show(); //this.Focus(); } protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) { UpdateFlyoutWindowPosition(); base.OnRenderSizeChanged(sizeInfo); } void _flyoutWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) { _flyoutWindow.Closing -= new System.ComponentModel.CancelEventHandler(_flyoutWindow_Closing); _flyoutWindow.Owner = null; _wndInteropWrapper.AttachedObject = null; } void UpdateFlyoutWindowPosition() { UpdateFlyoutWindowPosition(false); } void UpdateFlyoutWindowPosition(bool initialSetup) { if (_flyoutWindow == null) return; Debug.WriteLine("_leftAnchorTabPanel " + _leftAnchorTabPanel.ActualWidth + " - " + _leftAnchorTabPanel.Children.Count); double leftTabsWidth = FlowDirection == FlowDirection.LeftToRight ? _leftAnchorTabPanel.ActualWidth : _rightAnchorTabPanel.ActualWidth; double rightTabsWidth = FlowDirection == FlowDirection.LeftToRight ? _rightAnchorTabPanel.ActualWidth : _leftAnchorTabPanel.ActualWidth; double topTabsHeight = _topAnchorTabPanel.ActualHeight; double bottomTabsHeight = _bottomAnchorTabPanel.ActualHeight; Point locDockingManager = HelperFunc.PointToScreenWithoutFlowDirection(this, new Point()); double resWidth = initialSetup ? ResizingPanel.GetResizeWidth(_flyoutWindow.ReferencedPane).Value : _flyoutWindow.Width; double resHeight = initialSetup ? ResizingPanel.GetResizeHeight(_flyoutWindow.ReferencedPane).Value : _flyoutWindow.Height; //double resWidth = initialSetup ? ResizingPanel.GetEffectiveSize(_flyoutWindow.ReferencedPane).Width : _flyoutWindow.Width; //double resHeight = initialSetup ? ResizingPanel.GetEffectiveSize(_flyoutWindow.ReferencedPane).Height : _flyoutWindow.Height; _flyoutWindow.MinLeft = locDockingManager.X; _flyoutWindow.MinTop = locDockingManager.Y; if (_flyoutWindow.ReferencedPane.Anchor == AnchorStyle.Right) { _flyoutWindow.Top = locDockingManager.Y + topTabsHeight; _flyoutWindow.Height = this.ActualHeight - topTabsHeight - bottomTabsHeight; _flyoutWindow.MaxWidth = ActualWidth - rightTabsWidth; _flyoutWindow.MaxHeight = ActualHeight; if (initialSetup) { _flyoutWindow.Left = FlowDirection == FlowDirection.LeftToRight ? locDockingManager.X + this.ActualWidth - rightTabsWidth : locDockingManager.X + leftTabsWidth; _flyoutWindow.Width = 0.0; _flyoutWindow.TargetWidth = resWidth; } else { if (!_flyoutWindow.IsOpening && !_flyoutWindow.IsClosing) _flyoutWindow.Left = FlowDirection == FlowDirection.LeftToRight ? locDockingManager.X + this.ActualWidth - rightTabsWidth - _flyoutWindow.Width : locDockingManager.X + leftTabsWidth; } } if (_flyoutWindow.ReferencedPane.Anchor == AnchorStyle.Left) { _flyoutWindow.Top = locDockingManager.Y + topTabsHeight; _flyoutWindow.Height = this.ActualHeight - topTabsHeight - bottomTabsHeight; _flyoutWindow.MaxWidth = ActualWidth - leftTabsWidth; _flyoutWindow.MaxHeight = ActualHeight; if (initialSetup) { _flyoutWindow.Left = FlowDirection == FlowDirection.RightToLeft ? locDockingManager.X + this.ActualWidth - rightTabsWidth : locDockingManager.X + leftTabsWidth; _flyoutWindow.Width = 0.0; _flyoutWindow.TargetWidth = resWidth; } else { if (!_flyoutWindow.IsOpening && !_flyoutWindow.IsClosing) _flyoutWindow.Left = FlowDirection == FlowDirection.RightToLeft ? locDockingManager.X + this.ActualWidth - rightTabsWidth - _flyoutWindow.Width : locDockingManager.X + leftTabsWidth; } } if (_flyoutWindow.ReferencedPane.Anchor == AnchorStyle.Top) { _flyoutWindow.Left = locDockingManager.X + leftTabsWidth; _flyoutWindow.Width = this.ActualWidth - rightTabsWidth -leftTabsWidth; _flyoutWindow.MaxWidth = ActualWidth; _flyoutWindow.MaxHeight = ActualHeight - topTabsHeight; if (initialSetup) { _flyoutWindow.Height = 0.0; _flyoutWindow.TargetHeight = resHeight; } else { if (!_flyoutWindow.IsOpening && !_flyoutWindow.IsClosing) _flyoutWindow.Top = locDockingManager.Y + topTabsHeight; } } if (_flyoutWindow.ReferencedPane.Anchor == AnchorStyle.Bottom) { _flyoutWindow.Left = locDockingManager.X + leftTabsWidth; _flyoutWindow.Width = this.ActualWidth - rightTabsWidth - leftTabsWidth; _flyoutWindow.MaxWidth = ActualWidth; _flyoutWindow.MaxHeight = ActualHeight - bottomTabsHeight; if (initialSetup) { _flyoutWindow.Top = locDockingManager.Y + this.ActualHeight - bottomTabsHeight; _flyoutWindow.Height = 0.0; _flyoutWindow.TargetHeight = resHeight; } else { if (!_flyoutWindow.IsOpening && !_flyoutWindow.IsClosing) _flyoutWindow.Top = locDockingManager.Y + this.ActualHeight - bottomTabsHeight - _flyoutWindow.Height; if (_flyoutWindow.IsClosing) _flyoutWindow.Top = locDockingManager.Y + this.ActualHeight - bottomTabsHeight - _flyoutWindow.Height; } } if (_flyoutWindow != null && !_flyoutWindow.IsClosing) _flyoutWindow.UpdateClipRegion(); } void _wndInteropWrapper_OnWindowPosChanging(object sender, EventArgs e) { UpdateFlyoutWindowPosition(); } #endregion #region DragDrop Operations /// <summary> /// Begins dragging operations /// </summary> /// <param name="floatingWindow">Floating window containing pane which is dragged by user</param> /// <param name="point">Current mouse position</param> /// <param name="offset">Offset to be use to set floating window screen position</param> /// <returns>Retruns True is drag is completed, false otherwise</returns> internal bool Drag(FloatingWindow floatingWindow, Point point, Point offset) { bool mouseCaptured = IsMouseCaptured; if (!mouseCaptured) mouseCaptured = CaptureMouse(); if (mouseCaptured) { floatingWindow.Owner = Window.GetWindow(this); DragPaneServices.StartDrag(floatingWindow, point, offset); return true; } return false; } internal void Drag(DocumentContent documentContent, Point point, Point offset) { if (CaptureMouse()) { DocumentFloatingWindow floatingWindow = new DocumentFloatingWindow(this, documentContent); Drag(floatingWindow, point, offset); } } internal void Drag(DockableContent dockableContent, Point point, Point offset) { if (CaptureMouse()) { DockableFloatingWindow floatingWindow = new DockableFloatingWindow(this, dockableContent); floatingWindow.Owner = Window.GetWindow(this); RegisterFloatingWindow(floatingWindow); Drag(floatingWindow, point, offset); } } internal void Drag(DockablePane dockablePane, Point point, Point offset) { if (CaptureMouse()) { DockableFloatingWindow floatingWindow = new DockableFloatingWindow(this, dockablePane); floatingWindow.Owner = Window.GetWindow(this); RegisterFloatingWindow(floatingWindow); Drag(floatingWindow, point, offset); } } protected override void OnMouseMove(MouseEventArgs e) { if (IsMouseCaptured) { DragPaneServices.MoveDrag(this.PointToScreenDPI(e.GetPosition(this))); if (_flyoutWindow != null) _flyoutWindow.UpdateClipRegion(); } base.OnMouseMove(e); } protected override void OnMouseUp(MouseButtonEventArgs e) { CompleteDragging(e.GetPosition(this)); base.OnMouseUp(e); } protected override void OnMouseLeave(MouseEventArgs e) { CompleteDragging(e.GetPosition(this)); base.OnMouseLeave(e); } /// <summary> /// Ends all previously initiated dragging operations /// </summary> /// <param name="ptEndDrag"></param> void CompleteDragging(Point ptEndDrag) { if (IsMouseCaptured) { DragPaneServices.EndDrag(this.PointToScreenDPI(ptEndDrag)); ReleaseMouseCapture(); } } DragPaneServices _dragPaneServices; internal DragPaneServices DragPaneServices { get { if (_dragPaneServices == null) _dragPaneServices = new DragPaneServices(this); return _dragPaneServices; } } #endregion #region IDropSurface public bool IsSurfaceVisible { get { //a DockingManager is always visible for drop a pane return true; } } /// <summary> /// Returns a rectangle where this surface is active /// </summary> public Rect SurfaceRectangle { get { if (PresentationSource.FromVisual(this) != null) return new Rect(HelperFunc.PointToScreenWithoutFlowDirection(this, new Point(0, 0)), new Size(ActualWidth, ActualHeight)); return Rect.Empty; } } /// <summary> /// Overlay window which shows docking placeholders /// </summary> OverlayWindow _overlayWindow; /// <summary> /// Returns current overlay window /// </summary> internal OverlayWindow OverlayWindow { get { if (_overlayWindow == null) _overlayWindow = new OverlayWindow(this); return _overlayWindow; } } /// <summary> /// Handles this sourface mouse entering (show current overlay window) /// </summary> /// <param name="point">Current mouse position</param> public void OnDragEnter(Point point) { if (OverlayWindow.IsVisible) return; OverlayWindow.Owner = DragPaneServices.FloatingWindow; //OverlayWindow.Left = PointToScreen(new Point(0, 0)).X; //OverlayWindow.Top = PointToScreen(new Point(0, 0)).Y; Point origPoint = HelperFunc.PointToScreenWithoutFlowDirection(this, new Point()); OverlayWindow.Left = origPoint.X; OverlayWindow.Top = origPoint.Y; OverlayWindow.Width = ActualWidth; OverlayWindow.Height = ActualHeight; OverlayWindow.Show(); } /// <summary> /// Handles mouse overing this surface /// </summary> /// <param name="point"></param> public void OnDragOver(Point point) { } /// <summary> /// Handles mouse leave event during drag (hide overlay window) /// </summary> /// <param name="point"></param> public void OnDragLeave(Point point) { OverlayWindow.Owner = null; OverlayWindow.Hide(); Window mainWindow = Window.GetWindow(this); if (mainWindow != null) mainWindow.Activate(); } /// <summary> /// Handler drop events /// </summary> /// <param name="point">Current mouse position</param> /// <returns>Returns alwasy false because this surface doesn't support direct drop</returns> public bool OnDrop(Point point) { return false; } #endregion #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion #region Persistence void SaveLayout(XmlWriter xmlWriter, DockablePane pane) { if (pane.Items.Count > 0) { xmlWriter.WriteStartElement("DockablePane"); //if (!double.IsInfinity(ResizingPanel.GetResizeWidth(pane))) // xmlWriter.WriteAttributeString("ResizeWidth", XmlConvert.ToString(ResizingPanel.GetResizeWidth(pane))); ////if (!double.IsInfinity(ResizingPanel.GetResizeHeight(pane))) // xmlWriter.WriteAttributeString("ResizeHeight", XmlConvert.ToString(ResizingPanel.GetResizeHeight(pane))); xmlWriter.WriteAttributeString("ResizeWidth", ResizingPanel.GetResizeWidth(pane).ToString()); xmlWriter.WriteAttributeString("ResizeHeight", ResizingPanel.GetResizeHeight(pane).ToString()); xmlWriter.WriteAttributeString("EffectiveSize", new SizeConverter().ConvertToInvariantString(ResizingPanel.GetEffectiveSize(pane))); xmlWriter.WriteAttributeString("Anchor", pane.Anchor.ToString()); Debug.Assert(pane.Items.Count > 0); foreach (DockableContent content in pane.Items) { SaveLayout(xmlWriter, content); } xmlWriter.WriteEndElement(); } } void SaveLayout(XmlWriter xmlWriter, DockableFloatingWindow flWindow) { xmlWriter.WriteStartElement("FloatingWindow"); xmlWriter.WriteAttributeString("IsDockableWindow", XmlConvert.ToString(flWindow.IsDockableWindow)); xmlWriter.WriteAttributeString("Top", XmlConvert.ToString(flWindow.Top)); xmlWriter.WriteAttributeString("Left", XmlConvert.ToString(flWindow.Left)); xmlWriter.WriteAttributeString("Width", XmlConvert.ToString(flWindow.Width)); xmlWriter.WriteAttributeString("Height", XmlConvert.ToString(flWindow.Height)); SaveLayout(xmlWriter, flWindow.HostedPane); xmlWriter.WriteEndElement(); } void SaveLayout(XmlWriter xmlWriter, DockableContent content) { Debug.Assert(!string.IsNullOrEmpty(content.Name), "DockableContent must have a Name to save its content.\n" + "Click Ignore to skip this element and continue with save." ); if (!string.IsNullOrEmpty(content.Name)) { xmlWriter.WriteStartElement("DockableContent"); xmlWriter.WriteAttributeString("Name", content.Name); xmlWriter.WriteAttributeString("AutoHide", XmlConvert.ToString(content.State == DockableContentState.AutoHide)); content.SaveLayout(xmlWriter); xmlWriter.WriteEndElement(); } } void SaveLayout(XmlWriter xmlWriter, DocumentPane pane) { xmlWriter.WriteStartElement("DocumentPanePlaceHolder"); foreach (ManagedContent content in pane.Items) { if (content is DockableContent) { DockableContent dockableContent = content as DockableContent; SaveLayout(xmlWriter, dockableContent); } } xmlWriter.WriteEndElement(); } void SaveLayout(XmlWriter xmlWriter, DocumentPaneResizingPanel panelToSerialize) { xmlWriter.WriteStartElement("DocumentPanePlaceHolder"); List<DockableContent> listOfFoundContents = new List<DockableContent>(); FindContents<DockableContent>(listOfFoundContents, panelToSerialize); foreach (DockableContent content in listOfFoundContents) { SaveLayout(xmlWriter, content); } xmlWriter.WriteEndElement(); } void SaveLayout(XmlWriter xmlWriter, ResizingPanel panelToSerialize) { xmlWriter.WriteStartElement("ResizingPanel"); //if (!double.IsInfinity(ResizingPanel.GetResizeWidth(panelToSerialize))) // xmlWriter.WriteAttributeString("ResizeWidth", XmlConvert.ToString(ResizingPanel.GetResizeWidth(panelToSerialize))); //if (!double.IsInfinity(ResizingPanel.GetResizeHeight(panelToSerialize))) // xmlWriter.WriteAttributeString("ResizeHeight", XmlConvert.ToString(ResizingPanel.GetResizeHeight(panelToSerialize))); xmlWriter.WriteAttributeString("ResizeWidth", ResizingPanel.GetResizeWidth(panelToSerialize).ToString()); xmlWriter.WriteAttributeString("ResizeHeight", ResizingPanel.GetResizeHeight(panelToSerialize).ToString()); xmlWriter.WriteAttributeString("EffectiveSize", new SizeConverter().ConvertToInvariantString(ResizingPanel.GetEffectiveSize(panelToSerialize))); xmlWriter.WriteAttributeString("Orientation", Convert.ToString(panelToSerialize.Orientation)); foreach (UIElement child in panelToSerialize.Children) { if (child is DockablePane) SaveLayout(xmlWriter, child as DockablePane); else if (child is DocumentPane) SaveLayout(xmlWriter, child as DocumentPane); else if (child is DocumentPaneResizingPanel) SaveLayout(xmlWriter, child as DocumentPaneResizingPanel); else if (child is ResizingPanel) SaveLayout(xmlWriter, child as ResizingPanel); } xmlWriter.WriteEndElement(); } /// <summary> /// Save layout as xml to a <see cref="TextWriter"/> /// </summary> /// <param name="textWriter">Text writter object which receive the xml text</param> /// <remarks>The writer is not closed.</remarks> public void SaveLayout(TextWriter textWriter) { XmlTextWriter sw = new XmlTextWriter(textWriter); sw.Formatting = Formatting.Indented; sw.Indentation = 4; SaveLayout(sw); } /// <summary> /// Save layout as xml to generic stream /// </summary> /// <param name="backendStream">Stream receiving the xml string</param> /// <remarks>The stream is not closed</remarks> public void SaveLayout(Stream backendStream) { XmlTextWriter sw = new XmlTextWriter(backendStream, Encoding.Default); sw.Formatting = Formatting.Indented; sw.Indentation = 4; SaveLayout(sw); } /// <summary> /// Save layout as xml text into a file /// </summary> /// <param name="filename">Path to the file</param> /// <remarks>The file is created as new or overwritten is already exist a file with same name.</remarks> public void SaveLayout(string filename) { using (FileStream stream = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite)) SaveLayout(stream); } /// <summary> /// Send layout configuration to a <see cref="XmlTextWriter"/> object /// </summary> /// <param name="sw">Object which stores the xml</param> /// <remarks>The writer is not closed.</remarks> public void SaveLayout(XmlWriter sw) { if (!_isControlLoaded) throw new InvalidOperationException("Unable to serialize docking layout while DockingManager control is unloaded"); sw.WriteStartElement("DockingManager"); if (Content is ResizingPanel) SaveLayout(sw, Content as ResizingPanel); else if (Content is DocumentPane) SaveLayout(sw, Content as DocumentPane); else if (Content is DocumentPaneResizingPanel) SaveLayout(sw, Content as DocumentPaneResizingPanel); sw.WriteStartElement("Hidden"); foreach (DockableContent content in _hiddenContents) { SaveLayout(sw, content); } sw.WriteEndElement(); sw.WriteStartElement("Windows"); foreach (DockableFloatingWindow flWindow in _floatingWindows) { SaveLayout(sw, flWindow); } sw.WriteEndElement(); sw.WriteEndElement();//dockingmanager sw.Flush(); } void DetachContentFromDockingManager(DockableContent content) { if (content.State == DockableContentState.AutoHide) { DockablePane parentContainer = content.Parent as DockablePane; if (parentContainer != null && parentContainer.Items.Count == 1) ToggleAutoHide(content.Parent as DockablePane); } if (content.State == DockableContentState.DockableWindow || content.State == DockableContentState.FloatingWindow) { DockablePane parentContainer = content.Parent as DockablePane; if (parentContainer != null && parentContainer.Items.Count == 1) { FloatingWindow floatingWindow = Window.GetWindow(content) as FloatingWindow; floatingWindow.Close(true); } } //this content can be hidden also if was contained in closed floating window if (content.State == DockableContentState.Hidden) Show(content); content.DetachFromContainerPane(); } public delegate void DeserializationCallbackHandler(object sender, DeserializationCallbackEventArgs e); public DeserializationCallbackHandler DeserializationCallback { get; set; } void ShowAllHiddenContents() { while (_hiddenContents.Count > 0) { Debug.Assert(_hiddenContents[0].State == DockableContentState.Hidden); Show(_hiddenContents[0]); } } void RestoreDocumentPaneLayout(XmlElement childElement, out DocumentPane mainExistingDocumentPane, out DocumentPaneResizingPanel existingDocumentPanel, DockableContent[] dockableContents) { mainExistingDocumentPane = (Content is DocumentPane) ? Content as DocumentPane : GetMainDocumentPane(Content as ResizingPanel); - existingDocumentPanel = mainExistingDocumentPane.GetParentDocumentPaneResizingPanel(); + if (mainExistingDocumentPane != null) + { + existingDocumentPanel = mainExistingDocumentPane.GetParentDocumentPaneResizingPanel(); + } + else + { + existingDocumentPanel = null; + } if (existingDocumentPanel != null) { if (existingDocumentPanel.Parent is ResizingPanel) { ((ResizingPanel)existingDocumentPanel.Parent).RemoveChild(existingDocumentPanel); } else if (existingDocumentPanel.Parent is DockingManager) { ((DockingManager)existingDocumentPanel.Parent).Content = null; } } else if (mainExistingDocumentPane != null) { if (mainExistingDocumentPane.Parent is ResizingPanel) { ((ResizingPanel)mainExistingDocumentPane.Parent).RemoveChild(mainExistingDocumentPane); } else if (mainExistingDocumentPane.Parent is DockingManager) { ((DockingManager)mainExistingDocumentPane.Parent).Content = null; } } foreach (XmlElement contentElement in childElement.ChildNodes) { if (contentElement.HasAttribute("Name")) { DockableContent foundContent = null; string contentName = contentElement.GetAttribute("Name"); foreach (DockableContent content in dockableContents) { if (content.Name == contentName) { foundContent = content; break; } } if (foundContent == null && DeserializationCallback != null) { DeserializationCallbackEventArgs e = new DeserializationCallbackEventArgs(contentName); DeserializationCallback(this, e); foundContent = e.Content; } if (foundContent != null) { DetachContentFromDockingManager(foundContent); mainExistingDocumentPane.Items.Add(foundContent); foundContent.SetStateToDocument(); //call custom layout persistence method foundContent.RestoreLayout(contentElement); } } } } ResizingPanel RestoreLayout(XmlElement panelElement, DockableContent[] dockableContents) { ResizingPanel panel = new ResizingPanel(); if (panelElement.HasAttribute("Orientation")) panel.Orientation = (Orientation)Enum.Parse(typeof(Orientation), panelElement.GetAttribute("Orientation")); foreach (XmlElement childElement in panelElement.ChildNodes) { if (childElement.Name == "ResizingPanel") { ResizingPanel childPanel = RestoreLayout(childElement, dockableContents); if (childElement.HasAttribute("ResizeWidth")) ResizingPanel.SetResizeWidth(childPanel, (GridLength)GLConverter.ConvertFromInvariantString(childElement.GetAttribute("ResizeWidth"))); if (childElement.HasAttribute("ResizeHeight")) ResizingPanel.SetResizeHeight(childPanel, (GridLength)GLConverter.ConvertFromInvariantString(childElement.GetAttribute("ResizeHeight"))); if (childElement.HasAttribute("EffectiveSize")) ResizingPanel.SetEffectiveSize(childPanel, (Size)(new SizeConverter()).ConvertFromInvariantString(childElement.GetAttribute("EffectiveSize"))); panel.Children.Add(childPanel); } #region Restore DockablePane else if (childElement.Name == "DockablePane") { DockablePane pane = new DockablePane(); if (childElement.HasAttribute("Anchor")) pane.Anchor = (AnchorStyle)Enum.Parse(typeof(AnchorStyle), childElement.GetAttribute("Anchor")); if (childElement.HasAttribute("ResizeWidth")) ResizingPanel.SetResizeWidth(pane, (GridLength)GLConverter.ConvertFromInvariantString(childElement.GetAttribute("ResizeWidth"))); if (childElement.HasAttribute("ResizeHeight")) ResizingPanel.SetResizeHeight(pane, (GridLength)GLConverter.ConvertFromInvariantString(childElement.GetAttribute("ResizeHeight"))); if (childElement.HasAttribute("EffectiveSize")) ResizingPanel.SetEffectiveSize(pane, (Size)(new SizeConverter()).ConvertFromInvariantString(childElement.GetAttribute("EffectiveSize"))); //storeWriter.WriteAttributeString( // "EffectiveSize", new SizeConverter().ConvertToInvariantString(ResizingPanel.GetEffectiveSize(ContainerPane))); bool toggleAutoHide = false; foreach (XmlElement contentElement in childElement.ChildNodes) { if (contentElement.HasAttribute("Name")) { DockableContent foundContent = null; string contentName = contentElement.GetAttribute("Name"); foreach (DockableContent content in dockableContents) { if (content.Name == contentName) { foundContent = content; break; } } if (foundContent == null && DeserializationCallback != null) { DeserializationCallbackEventArgs e = new DeserializationCallbackEventArgs(contentName); DeserializationCallback(this, e); foundContent = e.Content; } if (foundContent != null) { DetachContentFromDockingManager(foundContent); pane.Items.Add(foundContent); foundContent.SetStateToDock(); if (contentElement.HasAttribute("AutoHide") && XmlConvert.ToBoolean(contentElement.GetAttribute("AutoHide")) && pane.Items.Count == 1) toggleAutoHide = true; //call custom layout persistence method foundContent.RestoreLayout(contentElement); } } } if (pane.Items.Count > 0) { if (toggleAutoHide) ToggleAutoHide(pane); if (pane.Items.Count > 0) panel.Children.Add(pane); } } #endregion #region Restore Contents inside a DocumentPane else if (childElement.Name == "DocumentPanePlaceHolder") { DocumentPaneResizingPanel existingDocumentPanel = null; DocumentPane mainExistingDocumentPane = null; RestoreDocumentPaneLayout(childElement, out mainExistingDocumentPane, out existingDocumentPanel, dockableContents); if (existingDocumentPanel != null) { panel.Children.Add(existingDocumentPanel); } else if (mainExistingDocumentPane != null) { panel.Children.Add(mainExistingDocumentPane); } } #endregion } return panel; } public void RestoreLayout(Stream backendStream) { XmlDocument doc = new XmlDocument(); doc.Load(backendStream); RestoreLayout(doc); } public void RestoreLayout(XmlReader reader) { XmlDocument doc = new XmlDocument(); doc.Load(reader); RestoreLayout(doc); } public void RestoreLayout(string filename) { XmlDocument doc = new XmlDocument(); doc.Load(filename); RestoreLayout(doc); } public void RestoreLayout(TextReader reader) { XmlDocument doc = new XmlDocument(); doc.Load(reader); RestoreLayout(doc); } void RestoreLayout(XmlDocument doc) { if (!_isControlLoaded) throw new InvalidOperationException("Unable to deserialize a docking layout while DockingManager control is unloaded"); if (doc.DocumentElement == null || doc.DocumentElement.Name != "DockingManager") { Debug.Assert(false, "Layout file hasn't a valid structure!"); throw new InvalidOperationException("Layout file had not a valid structure!"); } if (doc.DocumentElement.ChildNodes.Count != 3 || (doc.DocumentElement.ChildNodes[0].Name != "ResizingPanel" && doc.DocumentElement.ChildNodes[0].Name != "DocumentPanePlaceHolder") || doc.DocumentElement.ChildNodes[1].Name != "Hidden" || doc.DocumentElement.ChildNodes[2].Name != "Windows") { Debug.Assert(false, "Layout file hasn't a valid structure!"); throw new InvalidOperationException("Layout file hasn't a valid structure!"); } //Hide temp windows HideAutoHideWindow(); HideNavigatorWindow(); HideDocumentNavigatorWindow(); DockableContent[] actualContents = DockableContents; //show all hidden contents ShowAllHiddenContents(); //restore main panel XmlElement rootElement = doc.DocumentElement.ChildNodes[0] as XmlElement; if (rootElement.Name == "ResizingPanel") { this.Content = RestoreLayout(rootElement, actualContents); } else if (rootElement.Name == "DocumentPanePlaceHolder") { DocumentPaneResizingPanel existingDocumentPanel = null; DocumentPane mainExistingDocumentPane = null; RestoreDocumentPaneLayout(rootElement, out mainExistingDocumentPane, out existingDocumentPanel, actualContents); if (existingDocumentPanel != null) { this.Content = existingDocumentPanel; } else if (mainExistingDocumentPane != null) { this.Content = mainExistingDocumentPane; } } //restore hidden contents foreach (XmlElement hiddenContentElement in doc.DocumentElement.ChildNodes[1].ChildNodes) { foreach (DockableContent hiddenContent in actualContents) { if (hiddenContentElement.GetAttribute("Name") == hiddenContent.Name && hiddenContent.State != DockableContentState.Hidden) { Hide(hiddenContent); hiddenContent.RestoreLayout(hiddenContentElement); } } } //restore floating windows foreach (XmlElement flWindowElement in doc.DocumentElement.ChildNodes[2].ChildNodes) { if (flWindowElement.ChildNodes.Count != 1) continue;//handles invalid layouts structures bool isDockableWindow = XmlConvert.ToBoolean(flWindowElement.GetAttribute("IsDockableWindow")); Point location = new Point(XmlConvert.ToDouble(flWindowElement.GetAttribute("Left")), XmlConvert.ToDouble(flWindowElement.GetAttribute("Top"))); Size size = new Size(XmlConvert.ToDouble(flWindowElement.GetAttribute("Width")), XmlConvert.ToDouble(flWindowElement.GetAttribute("Height"))); DockableFloatingWindow flWindow = new DockableFloatingWindow(this); flWindow.Left = location.X; flWindow.Top = location.Y; flWindow.Width = size.Width; flWindow.Height = size.Height; flWindow.Owner = Window.GetWindow(this); XmlElement paneElement = flWindowElement.ChildNodes[0] as XmlElement; FloatingDockablePane paneForFloatingWindow = new FloatingDockablePane(flWindow); if (paneElement.HasAttribute("ResizingWidth")) ResizingPanel.SetResizeWidth(paneForFloatingWindow, (GridLength)GLConverter.ConvertFromInvariantString(paneElement.GetAttribute("ResizeWidth"))); if (paneElement.HasAttribute("ResizingHeight")) ResizingPanel.SetResizeHeight(paneForFloatingWindow, (GridLength)GLConverter.ConvertFromInvariantString(paneElement.GetAttribute("ResizeHeight"))); paneForFloatingWindow.Anchor = (AnchorStyle)Enum.Parse(typeof(AnchorStyle), paneElement.GetAttribute("Anchor")); DockableContent contentToTransfer = null; foreach (XmlElement contentElement in paneElement.ChildNodes) { #region Find the content to transfer string contentToFindName = contentElement.GetAttribute("Name"); foreach (DockableContent content in actualContents) { if (contentToFindName == content.Name) { contentToTransfer = content; break; } } if (contentToTransfer == null && DeserializationCallback != null) { DeserializationCallbackEventArgs e = new DeserializationCallbackEventArgs(contentToFindName); DeserializationCallback(this, e); contentToTransfer = e.Content; } #endregion if (contentToTransfer != null) { DetachContentFromDockingManager(contentToTransfer); paneForFloatingWindow.Items.Add(contentToTransfer); contentToTransfer.RestoreLayout(contentElement); } } flWindow.HostedPane = paneForFloatingWindow; flWindow.IsDockableWindow = isDockableWindow; RegisterFloatingWindow(flWindow); flWindow.ApplyTemplate(); flWindow.Show(); } } /// <summary> /// Static converter used to convert GridLength from/to string /// </summary> static GridLengthConverter GLConverter = new GridLengthConverter(); #endregion #region OnClosing/OnClosedDocument events /// <summary> /// Event fired when the document is about to be closed /// </summary> public event EventHandler<CancelEventArgs> DocumentClosing; /// <summary> /// Event fired when a document has been closed /// </summary> /// <remarks>Note that when a document is closed, property like <see cref="ManagedContent.ContainerPane"/> or <see cref="ManagedContent.Manager"/> returns null.</remarks> public event EventHandler DocumentClosed; /// <summary> /// Ovveride this method to handle <see cref="DocumentClosing"/> event. /// </summary> protected virtual void OnDocumentClosing(CancelEventArgs e) { if (DocumentClosing != null && !e.Cancel) { DocumentClosing(this, e); } } /// <summary> /// Ovveride this method to handle <see cref="DocumentClosed"/> event. /// </summary> protected virtual void OnDocumentClosed() { if (DocumentClosed != null) DocumentClosed(this, EventArgs.Empty); } internal void FireDocumentClosingEvent(CancelEventArgs e) { OnDocumentClosing(e); } internal void FireDocumentClosedEvent() { OnDocumentClosed(); } public event EventHandler<RequestDocumentCloseEventArgs> RequestDocumentClose; internal bool FireRequestDocumentCloseEvent(DocumentContent doc) { bool res = false; if (RequestDocumentClose != null) { RequestDocumentCloseEventArgs args = new RequestDocumentCloseEventArgs(doc); RequestDocumentClose(this, args); res = !args.Cancel; } return res; } #endregion } } diff --git a/AvalonDock/AvalonDock/DocumentTabPanel.cs b/AvalonDock/AvalonDock/DocumentTabPanel.cs index 95edbd4..036691b 100644 --- a/AvalonDock/AvalonDock/DocumentTabPanel.cs +++ b/AvalonDock/AvalonDock/DocumentTabPanel.cs @@ -1,190 +1,105 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Diagnostics; using System.ComponentModel; namespace AvalonDock { [EditorBrowsable(EditorBrowsableState.Never)] public class DocumentTabPanel : PaneTabPanel { public static bool GetIsHeaderVisible(DependencyObject obj) { return (bool)obj.GetValue(IsHeaderVisibleProperty); } public static void SetIsHeaderVisible(DependencyObject obj, bool value) { obj.SetValue(IsHeaderVisibleProperty, value); } // Using a DependencyProperty as the backing store for IsHeaderVisible. This enables animation, styling, binding, etc... public static readonly DependencyProperty IsHeaderVisibleProperty = DependencyProperty.RegisterAttached("IsHeaderVisible", typeof(bool), typeof(DocumentTabPanel), new UIPropertyMetadata(false)); protected override Size MeasureOverride(Size availableSize) { Size desideredSize = new Size(0, availableSize.Height); int i = 1; foreach (ManagedContent child in Children) { Panel.SetZIndex(child, Selector.GetIsSelected(child)?1:-i); i++; child.Width = double.NaN; child.Height = double.NaN; child.Measure(new Size(double.PositiveInfinity, availableSize.Height)); desideredSize.Width += child.DesiredSize.Width; } return base.MeasureOverride(availableSize); //return desideredSize; } protected override Size ArrangeOverride(Size finalSize) { double offset = 0.0; bool skipAllOthers = false; foreach (ManagedContent doc in Children) { if (skipAllOthers || offset + doc.DesiredSize.Width > finalSize.Width) { SetIsHeaderVisible(doc, false); doc.Arrange(new Rect()); skipAllOthers = true; } else { SetIsHeaderVisible(doc, true); doc.Arrange(new Rect(offset, 0.0, doc.DesiredSize.Width, finalSize.Height)); offset += doc.ActualWidth; } } return finalSize; - ////Check if selected content is visible - //bool selectedDocumentIsVisible = false; - //foreach (ManagedContent doc in Children) - //{ - // if (doc.IsSelected) - // { - // selectedDocumentIsVisible = true; - // break; - // } - - // offset += doc.DesiredSize.Width; - // if (offset + doc.DesiredSize.Width >= finalSize.Width) - // break; - //} - - //bool flag = false; - //ManagedContent selectedDocument = null; - //offset = 0; - - //if (!selectedDocumentIsVisible) - //{ - // //try to put it visible - // foreach (ManagedContent doc in Children) - // { - // if (doc.IsSelected) - // { - // selectedDocument = doc; - // selectedDocument.Arrange(new Rect(offset, 0, Math.Min(doc.DesiredSize.Width, finalSize.Width - offset), finalSize.Height)); - // //doc.Arrange(new Rect(offset, 0, finalSize.Width - offset, finalSize.Height)); - - // offset += doc.ActualWidth;// selectedDocument.DesiredSize.Width; - // break; - // } - // } - //} - - //foreach (FrameworkElement child in Children) - //{ - // if (!selectedDocumentIsVisible && child == selectedDocument) - // continue; - - // if (flag || offset + child.DesiredSize.Width > finalSize.Width) - // { - // if (!flag && selectedDocumentIsVisible) - // child.Arrange(new Rect(offset, 0, Math.Min(child.DesiredSize.Width, finalSize.Width - offset), finalSize.Height)); - // else - // child.Arrange(new Rect()); - - // flag = true; - // } - // else - // { - // child.Arrange(new Rect(offset, 0, Math.Min(child.DesiredSize.Width, finalSize.Width - offset), finalSize.Height)); - // //child.Arrange(new Rect(offset, 0, finalSize.Width - offset, finalSize.Height)); - // offset += child.ActualWidth; - // } - - - //} - - - ////return new Size(offset, finalSize.Height); - ////return base.ArrangeOverride(finalSize); - //return finalSize; } - - //protected override Visual GetVisualChild(int index) - //{ - // return base.GetVisualChild(VisualChildrenCount - index - 1); - // //return base.GetVisualChild(index); - //} - - - - //protected override void OnVisualChildrenChanged(DependencyObject visualAdded, DependencyObject visualRemoved) - //{ - // base.OnVisualChildrenChanged(visualAdded, visualRemoved); - - // if (visualAdded != null) - // { - // SetZIndex(visualAdded as UIElement, -Children.Count); - // //Debug.Assert(visualAdded is DocumentContent); - // } - - - //} } } diff --git a/AvalonDock/AvalonDock/HelperFunc.cs b/AvalonDock/AvalonDock/HelperFunc.cs index 7fee730..3d8373b 100644 --- a/AvalonDock/AvalonDock/HelperFunc.cs +++ b/AvalonDock/AvalonDock/HelperFunc.cs @@ -1,195 +1,206 @@ using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Controls; using System.Windows.Threading; using System.Threading; namespace AvalonDock { internal static class HelperFunc { //public static bool AreVeryClose(double v1, double v2) //{ // if (Math.Abs(v1 - v2) < 0.000001) // return true; // return false; //} public static bool AreClose(double v1, double v2) { if (v1 == v2) { return true; } double num = ((Math.Abs(v1) + Math.Abs(v2)) + 10.0) * 2.2204460492503131E-16; double num2 = v1 - v2; return ((-num < num2) && (num > num2)); } public static double MultiplyCheckNaN(double v1, double v2) { //inf * 0 = 1 if (double.IsInfinity(v1) && v2 == 0.0) return 1.0; if (double.IsInfinity(v2) && v1 == 0.0) return 1.0; return v1 * v2; } public static bool IsLessThen(double v1, double v2) { if (AreClose(v1, v2)) return false; return v1 < v2; } public static Point PointToScreenWithoutFlowDirection(FrameworkElement element, Point point) { if (FrameworkElement.GetFlowDirection(element) == FlowDirection.RightToLeft) { Point leftToRightPoint = new Point( element.ActualWidth - point.X, point.Y); return element.PointToScreenDPI(leftToRightPoint); } return element.PointToScreenDPI(point); } public static T FindVisualAncestor<T>(this DependencyObject obj, bool includeThis) where T : DependencyObject { if (!includeThis) obj = VisualTreeHelper.GetParent(obj); while (obj != null && (!(obj is T))) { obj = VisualTreeHelper.GetParent(obj); } return obj as T; } public static bool IsLogicalChildContained<T>(this DependencyObject obj) where T : DependencyObject { foreach (object child in LogicalTreeHelper.GetChildren(obj)) { if (child is T) return true; if (child is DependencyObject) { bool res = (child as DependencyObject).IsLogicalChildContained<T>(); if (res) return true; } } return false; } public static T GetLogicalChildContained<T>(this DependencyObject obj) where T : DependencyObject { foreach (object child in LogicalTreeHelper.GetChildren(obj)) { if (child is T) return child as T; if (child is DependencyObject) { T childFound = (child as DependencyObject).GetLogicalChildContained<T>(); if (childFound != null) return childFound; } } return null; } public static T FindAnotherLogicalChildContained<T>(this DependencyObject obj, UIElement childToExclude) where T : DependencyObject { foreach (object child in LogicalTreeHelper.GetChildren(obj)) { if (child is T && child != childToExclude) return child as T; if (child is DependencyObject) { T childFound = (child as DependencyObject).FindAnotherLogicalChildContained<T>(childToExclude); if (childFound != null) return childFound; } } return null; } public static DockablePane FindChildDockablePane(this DockingManager manager, AnchorStyle desideredAnchor) { foreach (UIElement childObject in LogicalTreeHelper.GetChildren(manager)) { DockablePane foundPane = FindChildDockablePane(childObject, desideredAnchor); if (foundPane != null) return foundPane; } return null; } static DockablePane FindChildDockablePane(UIElement parent, AnchorStyle desideredAnchor) { if (parent is DockablePane && ((DockablePane)parent).Anchor == desideredAnchor) return parent as DockablePane; if (parent is ResizingPanel) { foreach (UIElement childObject in ((ResizingPanel)parent).Children) { DockablePane foundPane = FindChildDockablePane(childObject, desideredAnchor); if (foundPane != null) return foundPane; } } return null; } public static Point PointToScreenDPI(this Visual visual, Point pt) { Point resultPt = visual.PointToScreen(pt); return TransformToDeviceDPI(visual, resultPt); } public static Point TransformToDeviceDPI(this Visual visual, Point pt) { Matrix m = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; return new Point(pt.X / m.M11, pt.Y /m.M22); } public static Size TransformFromDeviceDPI(this Visual visual, Size size) { Matrix m = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; return new Size(size.Width * m.M11, size.Height * m.M22); } public static Point TransformFromDeviceDPI(this Visual visual, Point pt) { Matrix m = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; return new Point(pt.X * m.M11, pt.Y * m.M22); } public static bool CanTransform(this Visual visual) { return PresentationSource.FromVisual(visual) != null; } + + + public static void CallMethod(this object o, string methodName, object[] args) + { + o.GetType().GetMethod(methodName).Invoke(o, null); + } + + public static T GetPropertyValue<T>(this object o, string propertyName) + { + return (T)o.GetType().GetProperty(propertyName).GetValue(o, null); + } } } diff --git a/AvalonDock/AvalonDock/ManagedContent.cs b/AvalonDock/AvalonDock/ManagedContent.cs index 03744ee..c005bf9 100644 --- a/AvalonDock/AvalonDock/ManagedContent.cs +++ b/AvalonDock/AvalonDock/ManagedContent.cs @@ -1,534 +1,558 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.ComponentModel; using System.Xml; using System.Windows.Forms.Integration; using System.Diagnostics; using System.Windows.Threading; using System.Threading; using System.Reflection; namespace AvalonDock { public abstract class ManagedContent : ContentControl, INotifyPropertyChanged { static ManagedContent() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml //DefaultStyleKeyProperty.OverrideMetadata(typeof(ManagedContent), new FrameworkPropertyMetadata(typeof(ManagedContent))); FocusableProperty.OverrideMetadata(typeof(ManagedContent), new FrameworkPropertyMetadata(true)); } public ManagedContent() { this.Loaded += new RoutedEventHandler(ManagedContent_Loaded); this.Unloaded += new RoutedEventHandler(ManagedContent_Unloaded); + this.LayoutUpdated += new EventHandler(ManagedContent_LayoutUpdated); } + + public void ManagedContent_LayoutUpdated(object sender, EventArgs e) + { + WindowsFormsHost contentHost = null; + + if (this.Content is UserControl) + { + UserControl usTemp = this.Content as UserControl; + + if (usTemp.Content is WindowsFormsHost) + contentHost = usTemp.Content as WindowsFormsHost; + } + else if (this.Content is WindowsFormsHost) + { + contentHost = this.Content as WindowsFormsHost; + } + + if (contentHost != null) + { + object childCtrl = contentHost.GetType().GetProperty("Child").GetValue(contentHost, null); + if (childCtrl != null) + { + childCtrl.CallMethod("Refresh", null); + } + } + } void ManagedContent_Loaded(object sender, RoutedEventArgs e) { } void ManagedContent_Unloaded(object sender, RoutedEventArgs e) { } public string Title { get { return (string)GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } // Using a DependencyProperty as the backing store for Title. This enables animation, styling, binding, etc... public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(ManagedContent)); //public string IconSource //{ // get { return (string)GetValue(IconSourceProperty); } // set { SetValue(IconSourceProperty, value); } //} //// Using a DependencyProperty as the backing store for Icon. This enables animation, styling, binding, etc... //public static readonly DependencyProperty IconSourceProperty = // DependencyProperty.Register("IconSource", typeof(string), typeof(ManagedContent)); /// <summary> /// Access to <see cref="IconProperty"/> dependency property /// </summary> public object Icon { get { return (object)GetValue(IconProperty); } set { SetValue(IconProperty, value); } } /// <summary> /// Select an icon object for the content /// </summary> public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(object), typeof(ManagedContent), new FrameworkPropertyMetadata(null, new CoerceValueCallback(OnCoerce_Icon))); private static object OnCoerce_Icon(DependencyObject o, object value) { if (value is string) { Uri iconUri; // try to resolve given value as an absolute URI if (Uri.TryCreate(value as String, UriKind.RelativeOrAbsolute, out iconUri)) { ImageSource img = new BitmapImage(iconUri); if (null != img) { GreyableImage icon = (o as ManagedContent).Icon as GreyableImage; if (null == icon) icon = new GreyableImage(); icon.Source = img; icon.Stretch = Stretch.None; icon.SnapsToDevicePixels = true; return icon; } } } return value; } /// <summary> /// Access to <see cref="DefaultFocusedElementProperty"/> /// </summary> public IInputElement DefaultElement { get { return (IInputElement)GetValue(DefaultFocusedElementProperty); } set { SetValue(DefaultFocusedElementProperty, value); } } /// <summary> /// Gets or sets an element which is focused by default when content is activated /// </summary> public static readonly DependencyProperty DefaultFocusedElementProperty = DependencyProperty.Register("DefaultElement", typeof(IInputElement), typeof(ManagedContent)); FrameworkElement _dragEnabledArea; protected FrameworkElement DragEnabledArea { get { return _dragEnabledArea; } } public override void OnApplyTemplate() { base.OnApplyTemplate(); _dragEnabledArea = GetTemplateChild("PART_DragArea") as FrameworkElement; if (_dragEnabledArea != null) { _dragEnabledArea.MouseDown += new MouseButtonEventHandler(OnDragMouseDown); _dragEnabledArea.MouseMove += new MouseEventHandler(OnDragMouseMove); _dragEnabledArea.MouseUp += new MouseButtonEventHandler(OnDragMouseUp); _dragEnabledArea.MouseLeave += new MouseEventHandler(OnDragMouseLeave); } } #region Mouse management protected virtual void OnDragStart(Point ptMouse, Point ptrelativeMouse) { } Point ptStartDrag; bool isMouseDown = false; protected Point StartDragPoint { get { return ptStartDrag; } } protected bool IsMouseDown { get { return isMouseDown; } } protected void ResetIsMouseDownFlag() { isMouseDown = false; } protected virtual void OnDragMouseDown(object sender, MouseButtonEventArgs e) { if (!e.Handled && Manager != null)// && State != DockableContentState.AutoHide) { isMouseDown = true; ptStartDrag = e.GetPosition((IInputElement)System.Windows.Media.VisualTreeHelper.GetParent(this)); } } protected virtual void OnDragMouseMove(object sender, MouseEventArgs e) { } protected virtual void OnDragMouseUp(object sender, MouseButtonEventArgs e) { isMouseDown = false; } Point ptRelativePosition; protected virtual void OnDragMouseLeave(object sender, MouseEventArgs e) { if (!e.Handled && IsMouseDown && Manager != null) { if (!IsMouseCaptured) { Point ptMouseMove = e.GetPosition(this); ManagedContent contentToSwap = null; if (ContainerPane != null) { foreach (ManagedContent content in ContainerPane.Items) { if (content == this) continue; HitTestResult res = VisualTreeHelper.HitTest(content, e.GetPosition(content)); if (res != null) { contentToSwap = content; break; } } } if (contentToSwap != null) { Pane containerPane = ContainerPane; int myIndex = containerPane.Items.IndexOf(this); ContainerPane.Items.RemoveAt(myIndex); int otherIndex = containerPane.Items.IndexOf(contentToSwap); containerPane.Items.RemoveAt(otherIndex); containerPane.Items.Insert(otherIndex, this); containerPane.Items.Insert(myIndex, contentToSwap); containerPane.SelectedItem = this; e.Handled = false; return; } else if (Math.Abs(ptMouseMove.X - StartDragPoint.X) > SystemParameters.MinimumHorizontalDragDistance || Math.Abs(ptMouseMove.Y - StartDragPoint.Y) > SystemParameters.MinimumVerticalDragDistance) { ptRelativePosition = e.GetPosition(DragEnabledArea); ResetIsMouseDownFlag(); OnDragStart(StartDragPoint, ptRelativePosition); e.Handled = true; } } } isMouseDown = false; } #endregion protected override void OnMouseDown(MouseButtonEventArgs e) { base.OnMouseDown(e); if (!e.Handled) { SetAsActive(); IInputElement focusedElement = e.Source as IInputElement; if (focusedElement != null) Keyboard.Focus(focusedElement); } } protected override void OnKeyDown(KeyEventArgs e) { if (e.Key == Key.Enter) { if (ContainerPane != null) ContainerPane.SelectedItem = this; } base.OnKeyDown(e); } public Pane ContainerPane { get { Pane containerPane = Parent as Pane; if (containerPane != null) return containerPane; return this.FindVisualAncestor<Pane>(false); } } internal DockingManager Manager { get { if (ContainerPane != null) return ContainerPane.GetManager(); return null; } } protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e) { base.OnGotKeyboardFocus(e); Debug.WriteLine(string.Format("[{0}].OnGotKeyboardFocus() Source={1} NewFocus={2} OldFocus={3}", this.Name, e.Source.GetType().ToString(), e.NewFocus.GetType().ToString(), e.OldFocus == null ? "<null>" : e.OldFocus.GetType().ToString())); if (Manager != null && this.IsKeyboardFocusWithin)// && Manager.ActiveContent != this) { Manager.ActiveContent = this; } } protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e) { Debug.WriteLine(string.Format("[{0}].OnLostKeyboardFocus() Source={1} NewFocus={2} OldFocus={3}", this.Name, e.Source.GetType().ToString(), e.NewFocus == null ? "<null>" : e.NewFocus.GetType().ToString(), e.OldFocus == null ? "<null>" : e.OldFocus.GetType().ToString())); base.OnLostKeyboardFocus(e); } bool _isActiveContent = false; /// <summary> /// Returns true if the content is the currently active content. /// </summary> /// <remarks>Use <see cref="SetAsActive"/> method to set a content as active.</remarks> public bool IsActiveContent { get { return _isActiveContent; } internal set { if (_isActiveContent != value) { _isActiveContent = value; NotifyPropertyChanged("IsActiveContent"); if (IsActiveContentChanged != null) IsActiveContentChanged(this, EventArgs.Empty); if (_isActiveContent && !IsKeyboardFocused) { Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(delegate { if (_isActiveContent && !IsKeyboardFocused) { if (this.Content is WindowsFormsHost) { //Use reflection in order to remove WinForms assembly reference WindowsFormsHost contentHost = this.Content as WindowsFormsHost; object childCtrl = contentHost.GetType().GetProperty("Child").GetValue(contentHost, null); if (childCtrl != null) { - Type winFormType = childCtrl.GetType(); - - bool focused = (bool)winFormType.GetProperty("Focused").GetValue(childCtrl, null); - if (!focused) + if (!childCtrl.GetPropertyValue<bool>("Focused")) { - winFormType.GetMethod("Focus").Invoke(childCtrl, null); + childCtrl.CallMethod("Focus", null); } } } else if (DefaultElement != null) { Debug.WriteLine("Try to set kb focus to " + DefaultElement); IInputElement kbFocused = Keyboard.Focus(DefaultElement); if (kbFocused != null) Debug.WriteLine("Focused element " + kbFocused); else Debug.WriteLine("No focused element"); } else if (this.Content is IInputElement) { //Debug.WriteLine("Try to set kb focus to " + this.Content.ToString()); //IInputElement kbFocused = Keyboard.Focus(this.Content as IInputElement); //if (kbFocused != null) // Debug.WriteLine("Focused element " + kbFocused); //else // Debug.WriteLine("No focused element"); } } })); } } } } public event EventHandler IsActiveContentChanged; /// <summary> /// Set the content as the active content /// </summary> /// <remarks>After this method returns property <see cref="IsActiveContent"/> returns true.</remarks> public void SetAsActive() { if (ContainerPane != null && Manager != null)// && Manager.ActiveContent != this) { ContainerPane.SelectedItem = this; ContainerPane.Focus(); if (Manager != null) Manager.ActiveContent = this; } } bool _isActiveDocument = false; /// <summary> /// Returns true if the document is the currently active document. /// </summary> /// <remarks>Use <see cref="SetAsActive"/> method to set a content as active.</remarks> public bool IsActiveDocument { get { return _isActiveDocument; } internal set { if (_isActiveDocument != value) { if (value) { if (ContainerPane != null) ContainerPane.SelectedItem = this; } _isActiveDocument = value; NotifyPropertyChanged("IsActiveDocument"); } } } bool _isLocked; /// <summary> /// Gets or sets a value indicating if this content is locked (readonly). /// </summary> public bool IsLocked { get { return _isLocked; } set { _isLocked = value; NotifyPropertyChanged("IsLocked"); } } Size _floatingWindowSize = Size.Empty; /// <summary> /// Gets or sets the size of the floating window which hosts this content /// </summary> public Size FloatingWindowSize { get { return _floatingWindowSize; } set { _floatingWindowSize = value; } } ResizeMode _floatingResizeMode = ResizeMode.CanResize; public ResizeMode FloatingResizeMode { get { return _floatingResizeMode; } set { _floatingResizeMode = value; } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion public bool IsCloseable { get { return (bool)GetValue(IsCloseableProperty); } set { SetValue(IsCloseableProperty, value); } } // Using a DependencyProperty as the backing store for IsCloseable. This enables animation, styling, binding, etc... public static readonly DependencyProperty IsCloseableProperty = DependencyProperty.Register("IsCloseable", typeof(bool), typeof(ManagedContent), new UIPropertyMetadata(true)); } } diff --git a/AvalonDock/AvalonDock/OverlayWindow.cs b/AvalonDock/AvalonDock/OverlayWindow.cs index ae20f3f..00af4da 100644 --- a/AvalonDock/AvalonDock/OverlayWindow.cs +++ b/AvalonDock/AvalonDock/OverlayWindow.cs @@ -1,387 +1,383 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.ComponentModel; using System.Windows.Markup; using System.Diagnostics; using System.Windows.Threading; using System.Windows.Media.Animation; namespace AvalonDock { public enum OverlayButtonHover { None, DropPaneInto, DropPaneLeft, DropPaneRight, DropPaneTop, DropPaneBottom, DropBorderLeft, DropBorderRight, DropBorderTop, DropBorderBottom, } public class OverlayWindow : Window, INotifyPropertyChanged { static OverlayWindow() { DefaultStyleKeyProperty.OverrideMetadata(typeof(OverlayWindow), new FrameworkPropertyMetadata(typeof(OverlayWindow))); Window.AllowsTransparencyProperty.OverrideMetadata(typeof(OverlayWindow), new FrameworkPropertyMetadata(true)); Window.WindowStyleProperty.OverrideMetadata(typeof(OverlayWindow), new FrameworkPropertyMetadata(WindowStyle.None)); Window.ShowInTaskbarProperty.OverrideMetadata(typeof(OverlayWindow), new FrameworkPropertyMetadata(false)); } public OverlayWindow() { } DockingManager _manager = null; public OverlayWindow(DockingManager manager) { _manager = manager; } public override void OnApplyTemplate() { base.OnApplyTemplate(); gridPaneRelativeDockingOptions = GetTemplateChild("PART_gridPaneRelativeDockingOptions") as FrameworkElement; selectionBox = GetTemplateChild("PART_SelectionBox") as FrameworkElement; owdBottom = new OverlayWindowDockingButton(GetTemplateChild("PART_btnDockBottom") as FrameworkElement, this); owdTop = new OverlayWindowDockingButton(GetTemplateChild("PART_btnDockTop") as FrameworkElement, this); owdLeft = new OverlayWindowDockingButton(GetTemplateChild("PART_btnDockLeft") as FrameworkElement, this); owdRight = new OverlayWindowDockingButton(GetTemplateChild("PART_btnDockRight") as FrameworkElement, this); owdPaneBottom = new OverlayWindowDockingButton(GetTemplateChild("PART_btnDockPaneBottom") as FrameworkElement, this); owdPaneTop = new OverlayWindowDockingButton(GetTemplateChild("PART_btnDockPaneTop") as FrameworkElement, this); owdPaneLeft = new OverlayWindowDockingButton(GetTemplateChild("PART_btnDockPaneLeft") as FrameworkElement, this); owdPaneRight = new OverlayWindowDockingButton(GetTemplateChild("PART_btnDockPaneRight") as FrameworkElement, this); owdPaneInto = new OverlayWindowDockingButton(GetTemplateChild("PART_btnDockPaneInto") as FrameworkElement, this); _manager.DragPaneServices.Register(owdBottom); _manager.DragPaneServices.Register(owdTop); _manager.DragPaneServices.Register(owdLeft); _manager.DragPaneServices.Register(owdRight); _manager.DragPaneServices.Register(owdPaneBottom); _manager.DragPaneServices.Register(owdPaneTop); _manager.DragPaneServices.Register(owdPaneLeft); _manager.DragPaneServices.Register(owdPaneRight); _manager.DragPaneServices.Register(owdPaneInto); } FrameworkElement gridPaneRelativeDockingOptions; FrameworkElement selectionBox; OverlayWindowDockingButton owdBottom; OverlayWindowDockingButton owdTop; OverlayWindowDockingButton owdLeft; OverlayWindowDockingButton owdRight; OverlayWindowDockingButton owdPaneBottom; OverlayWindowDockingButton owdPaneTop; OverlayWindowDockingButton owdPaneLeft; OverlayWindowDockingButton owdPaneRight; OverlayWindowDockingButton owdPaneInto; internal bool OnDrop(OverlayWindowDockingButton owdDock, Point point) { //user has dropped the floating window over a anchor button //create a new dockable pane to insert in the main layout Pane paneToAnchor = _manager.DragPaneServices.FloatingWindow.ClonePane(); //floating window is going to be closed.. if (owdDock == owdBottom) _manager.Anchor(paneToAnchor, AnchorStyle.Bottom); else if (owdDock == owdLeft) _manager.Anchor(paneToAnchor, AnchorStyle.Left); else if (owdDock == owdRight) _manager.Anchor(paneToAnchor, AnchorStyle.Right); else if (owdDock == owdTop) _manager.Anchor(paneToAnchor, AnchorStyle.Top); else if (owdDock == owdPaneTop) _manager.Anchor(paneToAnchor, CurrentDropPane, AnchorStyle.Top); else if (owdDock == owdPaneBottom) _manager.Anchor(paneToAnchor, CurrentDropPane, AnchorStyle.Bottom); else if (owdDock == owdPaneLeft) _manager.Anchor(paneToAnchor, CurrentDropPane, AnchorStyle.Left); else if (owdDock == owdPaneRight) _manager.Anchor(paneToAnchor, CurrentDropPane, AnchorStyle.Right); else if (owdDock == owdPaneInto) _manager.DropInto(paneToAnchor, CurrentDropPane); selectionBox.Visibility = Visibility.Hidden; return true; } Pane CurrentDropPane = null; public void ShowOverlayPaneDockingOptions(Pane pane) { - if (!IsVisible) - return; HideOverlayPaneDockingOptions(pane); //check if dockable on a document pane DockableStyle currentPaneDockableStyle = _manager.DragPaneServices.FloatingWindow.HostedPane.GetCumulativeDockableStyle(); //if current drop pane is a DocumentPane ... if (pane is DocumentPane && (currentPaneDockableStyle & DockableStyle.Document) == 0) return; if (pane is DockablePane && (currentPaneDockableStyle & DockableStyle.Dockable) == 0) return; Rect rectPane = pane.SurfaceRectangle; Point myScreenTopLeft = this.PointToScreenDPI(new Point(0, 0)); rectPane.Offset(-myScreenTopLeft.X, -myScreenTopLeft.Y);//relative to me gridPaneRelativeDockingOptions.SetValue(Canvas.LeftProperty, rectPane.Left + rectPane.Width / 2 - gridPaneRelativeDockingOptions.Width / 2); gridPaneRelativeDockingOptions.SetValue(Canvas.TopProperty, rectPane.Top + rectPane.Height / 2 - gridPaneRelativeDockingOptions.Height / 2); if (pane is DocumentPane) gridPaneRelativeDockingOptions.Visibility = Visibility.Visible; else { gridPaneRelativeDockingOptions.Visibility = !(_manager.DragPaneServices.FloatingWindow is DocumentFloatingWindow) ? Visibility.Visible : Visibility.Hidden; } owdBottom.Enabled = ((currentPaneDockableStyle & DockableStyle.BottomBorder) > 0); owdTop.Enabled = ((currentPaneDockableStyle & DockableStyle.TopBorder) > 0); owdLeft.Enabled = ((currentPaneDockableStyle & DockableStyle.LeftBorder) > 0); owdRight.Enabled = ((currentPaneDockableStyle & DockableStyle.RightBorder) > 0); if (pane is DocumentPane) owdPaneInto.Enabled = true; else owdPaneInto.Enabled = !(_manager.DragPaneServices.FloatingWindow is DocumentFloatingWindow); int destPaneChildCount = pane.Items.Count; owdPaneBottom.Enabled = owdPaneInto.Enabled && destPaneChildCount > 0; owdPaneTop.Enabled = owdPaneInto.Enabled && destPaneChildCount > 0; owdPaneLeft.Enabled = owdPaneInto.Enabled && destPaneChildCount > 0; owdPaneRight.Enabled = owdPaneInto.Enabled && destPaneChildCount > 0; CurrentDropPane = pane; } public void HideOverlayPaneDockingOptions(Pane surfaceElement) { - if (!IsVisible) - return; owdPaneBottom.Enabled = false; owdPaneTop.Enabled = false; owdPaneLeft.Enabled = false; owdPaneRight.Enabled = false; owdPaneInto.Enabled = false; gridPaneRelativeDockingOptions.Visibility = Visibility.Collapsed; CurrentDropPane = null; OverlayButtonHover = OverlayButtonHover.None; } protected override void OnDeactivated(EventArgs e) { selectionBox.Visibility = Visibility.Hidden; base.OnDeactivated(e); } protected override void OnActivated(EventArgs e) { base.OnActivated(e); DockableStyle currentPaneDockableStyle = _manager.DragPaneServices.FloatingWindow.HostedPane.GetCumulativeDockableStyle(); selectionBox.Visibility = Visibility.Hidden; owdBottom.Enabled = (currentPaneDockableStyle & DockableStyle.BottomBorder) > 0; owdTop.Enabled = (currentPaneDockableStyle & DockableStyle.TopBorder) > 0; owdLeft.Enabled = (currentPaneDockableStyle & DockableStyle.LeftBorder) > 0; owdRight.Enabled = (currentPaneDockableStyle & DockableStyle.RightBorder) > 0; } /// <summary> /// Shows a highlighting rectangle /// </summary> /// <param name="overlayWindowDockingButton"></param> /// <param name="point"></param> /// <returns></returns> internal void OnDragEnter(OverlayWindowDockingButton owdDock, Point point) { OnDragOver(owdDock, point); } /// <summary> /// Hides the highlighting rectangle /// </summary> /// <param name="overlayWindowDockingButton"></param> /// <param name="point"></param> /// <returns></returns> internal void OnDragLeave(OverlayWindowDockingButton owdDock, Point point) { selectionBox.Visibility = Visibility.Hidden; _manager.DragPaneServices.FloatingWindow.OnHideSelectionBox(); OverlayButtonHover = OverlayButtonHover.None; } internal void OnDragOver(OverlayWindowDockingButton owdDock, Point point) { if (selectionBox == null) return; Rect rectPane; if (owdDock == owdBottom || owdDock == owdLeft || owdDock == owdTop || owdDock == owdRight) rectPane = _manager.SurfaceRectangle; else rectPane = CurrentDropPane.SurfaceRectangle; double selectionBoxWidth = Math.Min( rectPane.Width / 2.0, ResizingPanel.GetEffectiveSize(_manager.DragPaneServices.FloatingWindow.HostedPane).Width); double selectionBoxHeight = Math.Min( rectPane.Height / 2.0, ResizingPanel.GetEffectiveSize(_manager.DragPaneServices.FloatingWindow.HostedPane).Height); Point myScreenTopLeft = this.PointToScreenDPI(new Point()); rectPane.Offset(-myScreenTopLeft.X, -myScreenTopLeft.Y);//relative to me if (owdDock == owdBottom || owdDock == owdPaneBottom) { selectionBox.SetValue(Canvas.LeftProperty, rectPane.Left); selectionBox.SetValue(Canvas.TopProperty, rectPane.Top + rectPane.Height - selectionBoxHeight); selectionBox.Width = rectPane.Width; selectionBox.Height = selectionBoxHeight; } if (owdDock == owdLeft || owdDock == owdPaneLeft) { selectionBox.SetValue(Canvas.LeftProperty, rectPane.Left); selectionBox.SetValue(Canvas.TopProperty, rectPane.Top); selectionBox.Width = selectionBoxWidth; selectionBox.Height = rectPane.Height; } if (owdDock == owdRight || owdDock == owdPaneRight) { selectionBox.SetValue(Canvas.LeftProperty, rectPane.Left + rectPane.Width - selectionBoxWidth); selectionBox.SetValue(Canvas.TopProperty, rectPane.Top); selectionBox.Width = selectionBoxWidth; selectionBox.Height = rectPane.Height; } if (owdDock == owdTop || owdDock == owdPaneTop) { selectionBox.SetValue(Canvas.LeftProperty, rectPane.Left); selectionBox.SetValue(Canvas.TopProperty, rectPane.Top); selectionBox.Width = rectPane.Width; selectionBox.Height = selectionBoxHeight; } if (owdDock == owdPaneInto) { selectionBox.SetValue(Canvas.LeftProperty, rectPane.Left); selectionBox.SetValue(Canvas.TopProperty, rectPane.Top); selectionBox.Width = rectPane.Width; selectionBox.Height = rectPane.Height; } if (owdDock == owdLeft) OverlayButtonHover = OverlayButtonHover.DropBorderLeft; else if (owdDock == owdRight) OverlayButtonHover = OverlayButtonHover.DropBorderRight; else if (owdDock == owdTop) OverlayButtonHover = OverlayButtonHover.DropBorderTop; else if (owdDock == owdBottom) OverlayButtonHover = OverlayButtonHover.DropBorderBottom; else if (owdDock == owdPaneInto) OverlayButtonHover = OverlayButtonHover.DropPaneInto; else if (owdDock == owdPaneRight) OverlayButtonHover = OverlayButtonHover.DropPaneRight; else if (owdDock == owdPaneTop) OverlayButtonHover = OverlayButtonHover.DropPaneTop; else if (owdDock == owdPaneLeft) OverlayButtonHover = OverlayButtonHover.DropPaneLeft; else if (owdDock == owdPaneBottom) OverlayButtonHover = OverlayButtonHover.DropPaneBottom; else OverlayButtonHover = OverlayButtonHover.None; selectionBox.Visibility = Visibility.Visible; _manager.DragPaneServices.FloatingWindow.OnShowSelectionBox(); } OverlayButtonHover _overlayButtonHover = OverlayButtonHover.None; public OverlayButtonHover OverlayButtonHover { get { return _overlayButtonHover; } set { _overlayButtonHover = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("OverlayButtonHover")); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion } } diff --git a/AvalonDock/AvalonDock/Properties/AssemblyInfo.cs b/AvalonDock/AvalonDock/Properties/AssemblyInfo.cs index 0efa24f..5eb5647 100644 --- a/AvalonDock/AvalonDock/Properties/AssemblyInfo.cs +++ b/AvalonDock/AvalonDock/Properties/AssemblyInfo.cs @@ -1,62 +1,62 @@ #region Using directives using System.Reflection; using System.Runtime.CompilerServices; using System.Resources; using System.Globalization; using System.Windows; using System.Runtime.InteropServices; #endregion // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AvalonDock")] [assembly: AssemblyDescription("WPF docking library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AvalonDock")] [assembly: AssemblyCopyright("Copyright @ Adolfo Marinucci 2007-2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] // Specifies the location in which theme dictionaries are stored for types in an assembly. [assembly: ThemeInfo( // Specifies the location of system theme-specific resource dictionaries for this project. // The default setting in this project is "None" since this default project does not // include these user-defined theme files: // Themes\Aero.NormalColor.xaml // Themes\Classic.xaml // Themes\Luna.Homestead.xaml // Themes\Luna.Metallic.xaml // Themes\Luna.NormalColor.xaml // Themes\Royale.NormalColor.xaml ResourceDictionaryLocation.SourceAssembly, // Specifies the location of the system non-theme specific resource dictionary: // Themes\generic.xaml ResourceDictionaryLocation.SourceAssembly)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: -[assembly: AssemblyVersion("1.2.2663")] +[assembly: AssemblyVersion("1.2.2691")]
icsharpcode/SharpDevelop-Vendor
9cea8b8c92624642eda42b4d9651b58f384629d0
Upload AvalonDock 1.2.2666 to vendor branch.
diff --git a/AvalonDock/AvalonDock/Converters.cs b/AvalonDock/AvalonDock/Converters.cs index bc2bcc9..8f9e498 100644 --- a/AvalonDock/AvalonDock/Converters.cs +++ b/AvalonDock/AvalonDock/Converters.cs @@ -1,61 +1,99 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows.Data; using System.IO; using System.Reflection; using System.Windows.Media; +using System.Windows; namespace AvalonDock { - internal class FindResourcePathConverter : IValueConverter + public class FindResourcePathConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) { return null; //return new Uri(@"DocumentHS.png", UriKind.Relative); } return value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } + /// <summary> + /// Converter from boolean values to visibility (inverse mode) + /// </summary> + [ValueConversion(typeof(object), typeof(Visibility))] + public class BoolToVisibilityConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, + System.Globalization.CultureInfo culture) + { + return System.Convert.ToBoolean(value) ? Visibility.Visible : + (parameter != null && ((string)parameter) == "Hidden" ? Visibility.Hidden : Visibility.Collapsed); + } + public object ConvertBack(object value, Type targetType, object parameter, + System.Globalization.CultureInfo culture) + { + return null; + } + } + + + public static class Converters + { + static BoolToVisibilityConverter _BoolToVisibilityConverter = null; + + public static BoolToVisibilityConverter BoolToVisibilityConverter + { + get + { + if (_BoolToVisibilityConverter == null) + _BoolToVisibilityConverter = new BoolToVisibilityConverter(); + + + return _BoolToVisibilityConverter; + } + } + + } } diff --git a/AvalonDock/AvalonDock/DockableContent.cs b/AvalonDock/AvalonDock/DockableContent.cs index 261ed67..4ca992b 100644 --- a/AvalonDock/AvalonDock/DockableContent.cs +++ b/AvalonDock/AvalonDock/DockableContent.cs @@ -1,571 +1,571 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Diagnostics; using System.Xml; namespace AvalonDock { /// <summary> /// Enumerates all the possible states of <see cref="DockableContent"/> /// </summary> public enum DockableContentState { /// <summary> /// Content is docked to a border of a <see cref="ResizingPanel"/> within as <see cref="DockingManager"/> control /// </summary> Docked, /// <summary> /// Content is hosted by a flyout window and is visible only when user move mouse over an anchor thumb located to a <see cref="DockingManager"/> controlo border /// </summary> AutoHide, /// <summary> /// Content is hosted by a floating window and user can redock is on its <see cref="DockingManager"/> container control /// </summary> DockableWindow, /// <summary> /// Content is hosted by a floating window that can't be docked to a its <see cref="DockingManager"/> container control /// </summary> FloatingWindow, /// <summary> /// Content is hosted into a <see cref="DocmumentPane"/> /// </summary> Document, /// <summary> /// Content is hidden /// </summary> Hidden, } /// <summary> /// Defines how a dockable content can be dragged over a docking manager /// </summary> /// <remarks>This style can be composed with the 'or' operator.</remarks> public enum DockableStyle : uint { /// <summary> /// Content is not dockable at all /// </summary> None = 0x0000, /// <summary> /// Dockable as document /// </summary> Document = 0x0001, /// <summary> /// Dockable to the left border of <see cref="DockingManager"/> /// </summary> LeftBorder = 0x0002, /// <summary> /// Dockable to the right border of <see cref="DockingManager"/> /// </summary> RightBorder = 0x0004, /// <summary> /// Dockable to the top border of <see cref="DockingManager"/> /// </summary> TopBorder = 0x0008, /// <summary> /// Dockable to the bottom border of <see cref="DockingManager"/> /// </summary> BottomBorder= 0x0010, /// <summary> /// A <see cref="DockableContent"/> with this style can be hosted in a <see cref="FloatingWindow"/> /// </summary> Floating = 0x0020, /// <summary> /// A <see cref="DockableContent"/> with this style can be the only one content in a <see cref="DockablePane"/> pane (NOT YET SUPPORTED) /// </summary> /// <remarks>This style is not compatible with <see cref="DockableStyle.Document"/> style</remarks> Single = 0x0040, /// <summary> /// A <see cref="DockableContet"/> with this style can be autohidden. /// </summary> AutoHide = 0x0080, /// <summary> /// Dockable only to a border of a <see cref="DockingManager"/> /// </summary> DockableToBorders = LeftBorder | RightBorder | TopBorder | BottomBorder | AutoHide, /// <summary> /// Dockable to a border of a <see cref="DockingManager"/> and into a <see cref="DocumentPane"/> /// </summary> Dockable = DockableToBorders | Document | Floating, /// <summary> /// Dockable to a border of a <see cref="DockingManager"/> and into a <see cref="DocumentPane"/> but not in autohidden mode (WinForms controls) /// </summary> DockableButNotAutoHidden = Dockable & ~AutoHide } /// <summary> /// Represent a state of a dockable content that can be used to restore it after it's hidden /// </summary> internal class DockableContentStateAndPosition { public readonly Pane ContainerPane = null; public readonly int ChildIndex = -1; public readonly double Width; public readonly double Height; public readonly AnchorStyle Anchor = AnchorStyle.None; public DockableContentStateAndPosition( Pane containerPane, int childIndex, double width, double height, AnchorStyle anchor) { ContainerPane = containerPane; ChildIndex = childIndex; Width = Math.Max(width, 100.0); Height = Math.Max(height, 100.0); Anchor = anchor; } public DockableContentStateAndPosition( DockableContent cntToSave) { ContainerPane = cntToSave.ContainerPane; ChildIndex = ContainerPane.Items.IndexOf(cntToSave); Width = Math.Max(ContainerPane.ActualWidth, 100.0); Height = Math.Max(ContainerPane.ActualHeight, 100.0); DockablePane dockablePane = ContainerPane as DockablePane; if (dockablePane != null) { Anchor = dockablePane.Anchor; } } } /// <summary> /// Identifies a content that can be drag over a <see cref="DockingManager"/> control or hosted by a window floating over it (<see cref="FloatingWindow"/>). /// </summary> public class DockableContent : ManagedContent { static DockableContent() { DefaultStyleKeyProperty.OverrideMetadata(typeof(DockableContent), new FrameworkPropertyMetadata(typeof(DockableContent))); } public DockableContent() { } #region Drag content protected override void OnDragMouseMove(object sender, MouseEventArgs e) { base.OnDragMouseMove(sender, e); } protected override void OnDragStart(Point ptMouse, Point ptRelativeMouse) { if (DockableStyle != DockableStyle.None && State != DockableContentState.AutoHide) { Manager.Drag(this, HelperFunc.PointToScreenWithoutFlowDirection(this, ptMouse), ptRelativeMouse); } base.OnDragStart(ptMouse, ptRelativeMouse); } #endregion #region State Properties & Events public delegate void DockableContentStateHandler(object sender, DockableContentState state); public event DockableContentStateHandler StateChanged; public DockableContentState State { get { return (DockableContentState)GetValue(StatePropertyKey.DependencyProperty); } //protected set { SetValue(StatePropertyKey, value); } protected set { SetValue(StatePropertyKey, value); if (StateChanged != null) StateChanged(this, value); } } // Using a DependencyProperty as the backing store for State. This enables animation, styling, binding, etc... public static readonly DependencyPropertyKey StatePropertyKey = DependencyProperty.RegisterReadOnly("State", typeof(DockableContentState), typeof(DockableContent), new UIPropertyMetadata(DockableContentState.Docked)); DockableStyle _dockableStyle = DockableStyle.Dockable; /// <summary> /// Get or sets a value that indicates how a dockable content can be dragged over and docked to a <see cref="DockingManager"/> /// </summary> public DockableStyle DockableStyle { get { return _dockableStyle; } set { _dockableStyle = value; } } #endregion #region StateMachine internal void SetStateToAutoHide() { State = DockableContentState.AutoHide; } internal void SetStateToDock() { State = DockableContentState.Docked; } internal void SetStateToDockableWindow() { if (State == DockableContentState.DockableWindow) return; Debug.Assert( State == DockableContentState.Document || State == DockableContentState.Docked || State == DockableContentState.FloatingWindow); State = DockableContentState.DockableWindow; } internal void SetStateToFloatingWindow() { if (State == DockableContentState.FloatingWindow) return; Debug.Assert( State == DockableContentState.Document || State == DockableContentState.Docked || State == DockableContentState.DockableWindow); State = DockableContentState.FloatingWindow; } internal void SetStateToHidden() { State = DockableContentState.Hidden; } internal void SetStateToDocument() { State = DockableContentState.Document; } #endregion #region HideOnClose public static DependencyProperty HideOnCloseKey = DependencyProperty.Register("HideOnClose", typeof(bool), typeof(DockableContent), new PropertyMetadata(true)); public bool HideOnClose { get { return (bool)GetValue(HideOnCloseKey); } set { SetValue(HideOnCloseKey, value); } } #endregion protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); this.CommandBindings.Add( new CommandBinding(FloatingCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(DockableCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(ShowAsDocumentCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(DockablePane.ToggleAutoHideCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(HideCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); } #region Commands static object syncRoot = new object(); private static RoutedUICommand documentCommand = null; public static RoutedUICommand ShowAsDocumentCommand { get { lock (syncRoot) { if (null == documentCommand) { documentCommand = new RoutedUICommand("Tabbed Document", "Document", typeof(DockableContent)); } } return documentCommand; } } private static RoutedUICommand dockableCommand = null; public static RoutedUICommand DockableCommand { get { lock (syncRoot) { if (null == dockableCommand) { dockableCommand = new RoutedUICommand("Dockable", "Dockable", typeof(DockablePane)); } } return dockableCommand; } } private static RoutedUICommand floatingCommand = null; public static RoutedUICommand FloatingCommand { get { lock (syncRoot) { if (null == floatingCommand) { floatingCommand = new RoutedUICommand("F_loating", "Floating", typeof(DockableContent)); } } return floatingCommand; } } private static RoutedUICommand hideCommand = null; public static RoutedUICommand HideCommand { get { lock (syncRoot) { if (null == hideCommand) { hideCommand = new RoutedUICommand("H_ide", "Hide", typeof(DockableContent)); } } return hideCommand; } } internal virtual void OnExecuteCommand(object sender, ExecutedRoutedEventArgs e) { if (!e.Handled && e.Command == DockablePane.ToggleAutoHideCommand) { if ((DockableStyle & DockableStyle.AutoHide) > 0) { ((ContainerPane as DockablePane)).ToggleAutoHide(); e.Handled = true; } } else if (!e.Handled && e.Command == DockableContent.HideCommand) { - //Manager.Hide(this); + Manager.Hide(this); e.Handled = true; } else if (!e.Handled && e.Command == DockableContent.FloatingCommand) { Manager.Show(this, DockableContentState.FloatingWindow); e.Handled = true; } else if (!e.Handled && e.Command == DockableContent.DockableCommand) { Manager.Show(this, DockableContentState.DockableWindow); e.Handled = true; } else if (!e.Handled && e.Command == DockableContent.ShowAsDocumentCommand) { Manager.Show(this, DockableContentState.Document); e.Handled = true; } } protected virtual void OnCanExecuteCommand(object sender, CanExecuteRoutedEventArgs e) { if (State == DockableContentState.AutoHide) { if (e.Command == DockablePane.ToggleAutoHideCommand || e.Command == DockablePane.CloseCommand || e.Command == DockableContent.HideCommand) e.CanExecute = true; else e.CanExecute = false; } else e.CanExecute = true; } #endregion #region Operations on content /// <summary> /// Remove this content from its parent container pane /// </summary> /// <returns></returns> internal DockableContent DetachFromContainerPane() { if (ContainerPane != null) { int indexOfContent = ContainerPane.Items.IndexOf(this); return ContainerPane.RemoveContent(indexOfContent) as DockableContent; } return null; } DockableContentStateAndPosition _savedStateAndPosition = null; internal DockableContentStateAndPosition SavedStateAndPosition { get { return _savedStateAndPosition; } } internal void SaveCurrentStateAndPosition() { //if (State == DockableContentState.Docked) //{ _savedStateAndPosition = new DockableContentStateAndPosition( this); //} //else //{ // _savedStateAndPosition = null; //} } /// <summary> /// Reset internal state and position of the content /// </summary> /// <remarks>After a <see cref="DockableContent"/> is hidden AvalonDock save its state and position in order to /// restore it correctly when user wants to reshow it calling <see cref="DockingManager.Show"/> function. Call this method /// if you want to reset these data and provide your state and anchor style calling one of the overloads of the function /// <see cref="DockingManager.Show"/>.</remarks> public void ResetSavedStateAndPosition() { _savedStateAndPosition = null; } #endregion #region Save/Restore Content Layout /// <summary> /// Save content specific layout settings /// </summary> /// <param name="storeWriter">Backend store writer</param> /// <remarks>Custom derived class can overloads this method to handle custom layout persistence.</remarks> public virtual void SaveLayout(XmlWriter storeWriter) { if (!FloatingWindowSize.IsEmpty) { storeWriter.WriteAttributeString( "FloatingWindowSize", new SizeConverter().ConvertToInvariantString(FloatingWindowSize)); } if (SavedStateAndPosition != null) { storeWriter.WriteAttributeString( "ChildIndex", SavedStateAndPosition.ChildIndex.ToString()); storeWriter.WriteAttributeString( "Width", SavedStateAndPosition.Width.ToString()); storeWriter.WriteAttributeString( "Height", SavedStateAndPosition.Height.ToString()); storeWriter.WriteAttributeString( "Anchor", SavedStateAndPosition.Anchor.ToString()); } } /// <summary> /// Restore content specific layout settings /// </summary> /// <param name="storeReader">Saved xml element containg content layout settings</param> /// <remarks>Custom derived class must overload this method to restore custom layout settings previously saved trought <see cref="SaveLayout"/>.</remarks> public virtual void RestoreLayout(XmlElement contentElement) { if (contentElement.HasAttribute("FloatingWindowSize")) FloatingWindowSize = (Size)(new SizeConverter()).ConvertFromInvariantString(contentElement.GetAttribute("FloatingWindowSize")); Size effectiveSize = new Size(0d, 0d); if (contentElement.HasAttribute("EffectiveSize")) { // Store effectiveSize = (Size)(new SizeConverter()).ConvertFromInvariantString(contentElement.GetAttribute("EffectiveSize")); } ResizingPanel.SetEffectiveSize(this, effectiveSize); if (contentElement.HasAttribute("ChildIndex")) { _savedStateAndPosition = new DockableContentStateAndPosition( ContainerPane, int.Parse(contentElement.GetAttribute("ChildIndex")), double.Parse(contentElement.GetAttribute("Width")), double.Parse(contentElement.GetAttribute("Height")), (AnchorStyle) Enum.Parse(typeof(AnchorStyle), contentElement.GetAttribute("Anchor")) ); } } #endregion } } diff --git a/AvalonDock/AvalonDock/DockableFloatingWindow.cs b/AvalonDock/AvalonDock/DockableFloatingWindow.cs index e0d0c08..f1374d1 100644 --- a/AvalonDock/AvalonDock/DockableFloatingWindow.cs +++ b/AvalonDock/AvalonDock/DockableFloatingWindow.cs @@ -1,274 +1,278 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.ComponentModel; using System.Windows.Markup; using System.Diagnostics; using System.Windows.Threading; using System.Windows.Media.Animation; using System.Windows.Interop; namespace AvalonDock { public class DockableFloatingWindow : FloatingWindow { static DockableFloatingWindow() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml DefaultStyleKeyProperty.OverrideMetadata(typeof(DockableFloatingWindow), new FrameworkPropertyMetadata(typeof(DockableFloatingWindow))); } public DockableFloatingWindow(DockingManager manager) : base(manager) { } Pane _previousPane = null; int _arrayIndexPreviousPane = -1; public DockableFloatingWindow(DockingManager manager, DockableContent content) : this(manager) { //create a new temporary pane FloatingDockablePane pane = new FloatingDockablePane(this); //setup window size //Width = content.ContainerPane.ActualWidth; //Height = content.ContainerPane.ActualHeight; if (content.FloatingWindowSize.IsEmpty) content.FloatingWindowSize = new Size(content.ContainerPane.ActualWidth, content.ContainerPane.ActualHeight); Width = content.FloatingWindowSize.Width; Height = content.FloatingWindowSize.Height; //save current content position in container pane _previousPane = content.ContainerPane; _arrayIndexPreviousPane = _previousPane.Items.IndexOf(content); //pane.SetValue(ResizingPanel.ResizeWidthProperty, _previousPane.GetValue(ResizingPanel.ResizeWidthProperty)); //pane.SetValue(ResizingPanel.ResizeHeightProperty, _previousPane.GetValue(ResizingPanel.ResizeHeightProperty)); //remove content from container pane content.ContainerPane.RemoveContent(_arrayIndexPreviousPane); //add content to my temporary pane pane.Items.Add(content); //let templates access this pane HostedPane = pane; //Change state on contents IsDockableWindow = true; DocumentPane originalDocumentPane = _previousPane as DocumentPane; if (originalDocumentPane != null) originalDocumentPane.CheckContentsEmpty(); } public DockableFloatingWindow(DockingManager manager, DockablePane dockablePane) : this(manager) { //create a new temporary pane FloatingDockablePane pane = new FloatingDockablePane(this); //setup window size ManagedContent selectedContent = dockablePane.SelectedItem as ManagedContent; if (selectedContent != null && selectedContent.FloatingWindowSize.IsEmpty) selectedContent.FloatingWindowSize = new Size(dockablePane.ActualWidth, dockablePane.ActualHeight); if (selectedContent != null) { Width = selectedContent.FloatingWindowSize.Width; Height = selectedContent.FloatingWindowSize.Height; this.ResizeMode = selectedContent.FloatingResizeMode; } else { Width = dockablePane.ActualWidth; Height = dockablePane.ActualHeight; } //Width = dockablePane.ActualWidth; //Height = dockablePane.ActualHeight; ////save current content position in container pane //pane.SetValue(ResizingPanel.ResizeWidthProperty, dockablePane.GetValue(ResizingPanel.ResizeWidthProperty)); //pane.SetValue(ResizingPanel.ResizeHeightProperty, dockablePane.GetValue(ResizingPanel.ResizeHeightProperty)); int selectedIndex = dockablePane.SelectedIndex; //remove contents from container pane and insert in hosted pane while (dockablePane.Items.Count > 0) { ManagedContent content = dockablePane.RemoveContent(0); //add content to my temporary pane pane.Items.Add(content); } //let templates access this pane HostedPane = pane; HostedPane.SelectedIndex = selectedIndex; //Change state on contents IsDockableWindow = true; } protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); if (HostedPane == null) HostedPane = Content as FloatingDockablePane; if (HostedPane != null) { Content = HostedPane; } } + + protected override void OnClosed(EventArgs e) { base.OnClosed(e); - while (HostedPane.Items.Count > 0) + DockableContent[] cntsToClose = new DockableContent[HostedPane.Items.Count]; + HostedPane.Items.CopyTo(cntsToClose, 0); + + foreach (DockableContent cntToClose in cntsToClose) { - //Manager.Hide(HostedPane.Items[0] as DockableContent); - HostedPane.CloseOrHide(HostedPane.Items[0] as DockableContent); + HostedPane.CloseOrHide(HostedPane.Items[0] as DockableContent, ForcedClosing); } Manager.UnregisterFloatingWindow(this); } public override Pane ClonePane() { DockablePane paneToAnchor = new DockablePane(); //transfer the resizing panel sizes //paneToAnchor.SetValue(ResizingPanel.ResizeWidthProperty, // HostedPane.GetValue(ResizingPanel.ResizeWidthProperty)); //paneToAnchor.SetValue(ResizingPanel.ResizeHeightProperty, // HostedPane.GetValue(ResizingPanel.ResizeHeightProperty)); ResizingPanel.SetEffectiveSize(paneToAnchor, new Size(Width, Height)); int selectedIndex = HostedPane.SelectedIndex; //transfer contents from hosted pane in the floating window and //the new created dockable pane while (HostedPane.Items.Count > 0) { paneToAnchor.Items.Add( HostedPane.RemoveContent(0)); } paneToAnchor.SelectedIndex = selectedIndex; return paneToAnchor; } protected override void OnExecuteCommand(object sender, ExecutedRoutedEventArgs e) { if (e.Command == TabbedDocumentCommand) { DockableContent currentContent = HostedPane.SelectedItem as DockableContent; Manager.MainDocumentPane.Items.Insert(0, HostedPane.RemoveContent(HostedPane.SelectedIndex)); Manager.MainDocumentPane.SelectedIndex = 0; currentContent.SetStateToDocument(); if (HostedPane.Items.Count == 0) this.Close(); e.Handled = true; } else if (e.Command == CloseCommand) { //DockableContent currentContent = HostedPane.SelectedItem as DockableContent; //Manager.Hide(currentContent); HostedPane.CloseOrHide(); if (HostedPane.Items.Count == 0) this.Close(); e.Handled = true; } base.OnExecuteCommand(sender, e); } protected override void Redock() { if (_previousPane != null) { if (_previousPane.GetManager() == null) { DockablePane newContainerPane = new DockablePane(); newContainerPane.Items.Add(HostedPane.RemoveContent(0)); newContainerPane.SetValue(ResizingPanel.ResizeWidthProperty, _previousPane.GetValue(ResizingPanel.ResizeWidthProperty)); newContainerPane.SetValue(ResizingPanel.ResizeHeightProperty, _previousPane.GetValue(ResizingPanel.ResizeHeightProperty)); Manager.Anchor(newContainerPane, ((DockablePane)_previousPane).Anchor); } else { if (_arrayIndexPreviousPane > _previousPane.Items.Count) _arrayIndexPreviousPane = _previousPane.Items.Count; DockableContent currentContent = HostedPane.Items[0] as DockableContent; _previousPane.Items.Insert(_arrayIndexPreviousPane, HostedPane.RemoveContent(0)); _previousPane.SelectedIndex = _arrayIndexPreviousPane; currentContent.SetStateToDock(); } this.Close(); } base.Redock(); } } } diff --git a/AvalonDock/AvalonDock/DockablePane.cs b/AvalonDock/AvalonDock/DockablePane.cs index a58a746..d0188c7 100644 --- a/AvalonDock/AvalonDock/DockablePane.cs +++ b/AvalonDock/AvalonDock/DockablePane.cs @@ -1,499 +1,501 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Diagnostics; using System.ComponentModel; using System.Collections; namespace AvalonDock { /// <summary> /// Anchor types /// </summary> public enum AnchorStyle { /// <summary> /// No anchor style, while content is hosted in a <see cref="DocumentPane"/> or a <see cref="FloatingWindow"/> /// </summary> None, /// <summary> /// Top border anchor /// </summary> Top, /// <summary> /// Left border anchor /// </summary> Left, /// <summary> /// Bottom border anchor /// </summary> Bottom, /// <summary> /// Right border anchor /// </summary> Right } public class DockablePane : Pane { static DockablePane() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml DefaultStyleKeyProperty.OverrideMetadata(typeof(DockablePane), new FrameworkPropertyMetadata(typeof(DockablePane))); } protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); this.CommandBindings.Add( new CommandBinding(ShowOptionsCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(ToggleAutoHideCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(CloseCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); } public DockablePane() { this.Loaded += new RoutedEventHandler(DockablePane_Loaded); this.Unloaded += new RoutedEventHandler(DockablePane_Unloaded); } void DockablePane_Loaded(object sender, RoutedEventArgs e) { } void DockablePane_Unloaded(object sender, RoutedEventArgs e) { UnloadOptionsContextMenu(); } #region Dependency properties public bool ShowHeader { get { return (bool)GetValue(ShowHeaderProperty); } set { SetValue(ShowHeaderProperty, value); } } // Using a DependencyProperty as the backing store for ActiveContent. This enables animation, styling, binding, etc... public static readonly DependencyProperty ShowHeaderProperty = DependencyProperty.Register("ShowHeader", typeof(bool), typeof(DockablePane), new UIPropertyMetadata(true)); public bool ShowTabs { get { return (bool)GetValue(ShowTabsProperty); } set { SetValue(ShowTabsProperty, value); } } // Using a DependencyProperty as the backing store for ShowTabs. This enables animation, styling, binding, etc... public static readonly DependencyProperty ShowTabsProperty = DependencyProperty.Register("ShowTabs", typeof(bool), typeof(DockablePane), new UIPropertyMetadata(true)); public AnchorStyle Anchor { get { return (AnchorStyle)GetValue(AnchorPropertyKey.DependencyProperty); } internal set { SetValue(AnchorPropertyKey, value); } } // Using a DependencyProperty as the backing store for Anchor. This enables animation, styling, binding, etc... public static readonly DependencyPropertyKey AnchorPropertyKey = DependencyProperty.RegisterAttachedReadOnly("Anchor", typeof(AnchorStyle), typeof(DockablePane), new UIPropertyMetadata(AnchorStyle.None)); public override void OnApplyTemplate() { base.OnApplyTemplate(); if (_partHeader != null) { _partHeader.MouseDown += new MouseButtonEventHandler(OnHeaderMouseDown); _partHeader.MouseMove += new MouseEventHandler(OnHeaderMouseMove); _partHeader.MouseUp += new MouseButtonEventHandler(OnHeaderMouseUp); _partHeader.MouseEnter += new MouseEventHandler(OnHeaderMouseEnter); _partHeader.MouseLeave += new MouseEventHandler(OnHeaderMouseLeave); } _optionsContextMenuPlacementTarget = GetTemplateChild("PART_ShowContextMenuButton") as UIElement; } #endregion public override bool IsSurfaceVisible { get { foreach (ManagedContent managedContent in Items) { if (managedContent is DocumentContent) continue; if (((DockableContent)managedContent).State == DockableContentState.Docked) return true; } return false; } } #region OptionsContextMenu ContextMenu cxOptions = null; UIElement _optionsContextMenuPlacementTarget = null; void LoadOptionsContextMenu() { Debug.Assert(cxOptions == null); cxOptions = FindResource(new ComponentResourceKey(typeof(DockingManager), ContextMenuElement.DockablePane)) as ContextMenu; cxOptions.Opened += new RoutedEventHandler(cxOptions_RefreshOpenState); cxOptions.Closed += new RoutedEventHandler(cxOptions_RefreshOpenState); } void UnloadOptionsContextMenu() { if (cxOptions != null) { cxOptions.Opened -= new RoutedEventHandler(cxOptions_RefreshOpenState); cxOptions.Closed -= new RoutedEventHandler(cxOptions_RefreshOpenState); cxOptions = null; } } protected virtual void OpenOptionsContextMenu() { if (cxOptions == null) { LoadOptionsContextMenu(); } if (cxOptions != null) { + cxOptions.DataContext = this.SelectedItem as DockableContent; + foreach (MenuItem menuItem in cxOptions.Items) menuItem.CommandTarget = this.SelectedItem as DockableContent; if (_optionsContextMenuPlacementTarget != null) { cxOptions.Placement = PlacementMode.Bottom; cxOptions.PlacementTarget = _optionsContextMenuPlacementTarget; } else { cxOptions.Placement = PlacementMode.MousePoint; cxOptions.PlacementTarget = this; } cxOptions.IsOpen = true; } } void cxOptions_RefreshOpenState(object sender, RoutedEventArgs e) { NotifyPropertyChanged("IsOptionsMenuOpened"); } public bool IsOptionsMenuOpened { get { return cxOptions != null && cxOptions.IsOpen && ( _optionsContextMenuPlacementTarget != null ? cxOptions.PlacementTarget == _optionsContextMenuPlacementTarget : cxOptions.PlacementTarget == this); } } #endregion #region Mouse management void FocusContent() { ManagedContent selectedContent = SelectedItem as ManagedContent; if (selectedContent != null && selectedContent.Content is UIElement) { //UIElement internalContent = selectedContent.Content as UIElement; //bool res = internalContent.Focus(); selectedContent.SetAsActive(); } } Point ptStartDrag; bool isMouseDown = false; protected virtual void OnHeaderMouseDown(object sender, MouseButtonEventArgs e) { if (!e.Handled) { FocusContent(); if (((DockableContent)SelectedItem).State != DockableContentState.AutoHide) { ptStartDrag = e.MouseDevice.GetPosition(this); isMouseDown = true; } } } protected virtual void OnHeaderMouseMove(object sender, MouseEventArgs e) { Point ptMouseMove = e.GetPosition(this); if (!e.Handled && isMouseDown) { if (_partHeader != null && _partHeader.IsMouseOver) { if (!IsMouseCaptured) { if (Math.Abs(ptMouseMove.X - ptStartDrag.X) > SystemParameters.MinimumHorizontalDragDistance || Math.Abs(ptMouseMove.Y - ptStartDrag.Y) > SystemParameters.MinimumVerticalDragDistance) { isMouseDown = false; ReleaseMouseCapture(); DockingManager manager = GetManager(); manager.Drag(this, this.PointToScreenDPI(e.GetPosition(this)), e.GetPosition(this)); e.Handled = true; } } } } } protected virtual void OnHeaderMouseUp(object sender, MouseButtonEventArgs e) { isMouseDown = false; ReleaseMouseCapture(); } protected virtual void OnHeaderMouseEnter(object sender, MouseEventArgs e) { isMouseDown = false; } protected virtual void OnHeaderMouseLeave(object sender, MouseEventArgs e) { isMouseDown = false; } #endregion #region Commands private static object syncRoot = new object(); private static RoutedUICommand optionsCommand = null; public static RoutedUICommand ShowOptionsCommand { get { lock (syncRoot) { if (null == optionsCommand) { optionsCommand = new RoutedUICommand("S_how options", "Options", typeof(DockablePane)); } } return optionsCommand; } } private static RoutedUICommand autoHideCommand = null; public static RoutedUICommand ToggleAutoHideCommand { get { lock (syncRoot) { if (null == autoHideCommand) { autoHideCommand = new RoutedUICommand("A_utohide", "AutoHide", typeof(DockablePane)); } } return autoHideCommand; } } private static RoutedUICommand closeCommand = null; public static RoutedUICommand CloseCommand { get { lock (syncRoot) { if (null == closeCommand) { closeCommand = new RoutedUICommand("C_lose", "Close", typeof(DockablePane)); } } return closeCommand; } } internal virtual void OnExecuteCommand(object sender, ExecutedRoutedEventArgs e) { if (e.Command == ToggleAutoHideCommand) { ToggleAutoHide(); e.Handled = true; } else if (e.Command == CloseCommand) { CloseOrHide(); e.Handled = true; } else if (e.Command == ShowOptionsCommand) { OpenOptionsContextMenu(); e.Handled = true; } } protected virtual void OnCanExecuteCommand(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } #endregion public override bool IsDocked { get { return IsSurfaceVisible; } } public DockableStyle GetCumulativeDockableStyle() { DockableStyle style = DockableStyle.Dockable; if (Items.Count == 1 && Items[0] is DocumentContent) style = DockableStyle.Document; else { foreach (DockableContent content in this.Items) { style &= content.DockableStyle; } } return style; } public override ManagedContent RemoveContent(int index) { ManagedContent content = base.RemoveContent(index); if (Items.Count == 0) { ResizingPanel containerPanel = Parent as ResizingPanel; if (containerPanel != null) containerPanel.RemoveChild(this); } return content; } protected virtual void CheckItems(IList newItems) { foreach (object newItem in newItems) { if (!(newItem is DockableContent)) throw new InvalidOperationException("DockablePane can contain only DockableContents!"); } } protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (e.NewItems != null) CheckItems(e.NewItems); base.OnItemsChanged(e); } #region Dockable Pane operations /// <summary> /// Show/Hide a flyout window containing this pane /// </summary> internal virtual void ToggleAutoHide() { bool flag = true; foreach (DockableContent cnt in this.Items) { if ((cnt.DockableStyle & DockableStyle.AutoHide) == 0) { flag = false; break; } } if (flag && GetManager() != null) GetManager().ToggleAutoHide(this); } /// <summary> /// Closes or hides current content depending on HideOnClose property /// </summary> internal void CloseOrHide() { - CloseOrHide(SelectedItem as DockableContent); + CloseOrHide(SelectedItem as DockableContent, false); } #endregion } } diff --git a/AvalonDock/AvalonDock/DockingManager.cs b/AvalonDock/AvalonDock/DockingManager.cs index 30caddd..803eac5 100644 --- a/AvalonDock/AvalonDock/DockingManager.cs +++ b/AvalonDock/AvalonDock/DockingManager.cs @@ -1102,1024 +1102,1027 @@ namespace AvalonDock if (anchor == AnchorStyle.Left || anchor == AnchorStyle.Right) { double w = Math.Min( ResizingPanel.GetEffectiveSize(relativePane).Width / 2.0, ResizingPanel.GetEffectiveSize(paneToAnchor).Width); ResizingPanel.SetResizeWidth(paneToAnchor, new GridLength(w, GridUnitType.Pixel)); ResizingPanel.SetResizeHeight(paneToAnchor, new GridLength(1.0, GridUnitType.Star)); } else { double h = Math.Min( ResizingPanel.GetEffectiveSize(relativePane).Height / 2.0, ResizingPanel.GetEffectiveSize(paneToAnchor).Height); ResizingPanel.SetResizeWidth(paneToAnchor, new GridLength(1.0, GridUnitType.Star)); ResizingPanel.SetResizeHeight(paneToAnchor, new GridLength(h, GridUnitType.Pixel)); } //refresh contents state foreach (DockableContent draggedContent in paneToAnchor.Items) { draggedContent.SetStateToDock(); } //than set the new anchor style for the pane paneToAnchor.Anchor = anchor; paneToAnchor.Focus(); } /// <summary> /// Anchor a document pane (<see cref="DockablePane"/>) to a border of an other document pane /// </summary> /// <param name="paneToAnchor">Pane to anchor</param> /// <param name="relativePane">Pane relative</param> /// <param name="anchor"></param> public void Anchor(DocumentPane paneToAnchor, DocumentPane relativePane, AnchorStyle anchor) { if (anchor == AnchorStyle.None) anchor = AnchorStyle.Right; //get a reference to the resizingpanel container of relativePane ResizingPanel relativePaneContainer = LogicalTreeHelper.GetParent(relativePane) as ResizingPanel; DocumentPaneResizingPanel relativeDocumentPaneContainer = relativePane.GetParentDocumentPaneResizingPanel(); Orientation requestedOrientation = (anchor == AnchorStyle.Bottom || anchor == AnchorStyle.Top) ? Orientation.Vertical : Orientation.Horizontal; if (relativePaneContainer == null) { Debug.Assert(relativePane.Parent == this); relativeDocumentPaneContainer = new DocumentPaneResizingPanel(); relativePaneContainer = relativeDocumentPaneContainer; relativeDocumentPaneContainer.Orientation = requestedOrientation; this.Content = relativePaneContainer; relativePaneContainer.Children.Add(relativePane); } if (relativeDocumentPaneContainer == null) { relativeDocumentPaneContainer = new DocumentPaneResizingPanel(); relativeDocumentPaneContainer.Orientation = requestedOrientation; int indexOfPaneToReplace = relativePaneContainer.Children.IndexOf(relativePane); relativePaneContainer.Children.RemoveAt(indexOfPaneToReplace); relativeDocumentPaneContainer.Children.Add(relativePane); relativePaneContainer.Children.Insert(indexOfPaneToReplace, relativeDocumentPaneContainer); relativePaneContainer = relativeDocumentPaneContainer; } Debug.Assert(relativePaneContainer != null, "By now we can't have a pane without a resizing panel containing it"); #region Create and setup container panel if (relativePaneContainer != null) { //check if orientation is right if (relativePaneContainer.Orientation != requestedOrientation) { //if the existing panel is not oriented as we want //create a new one DocumentPaneResizingPanel newPanel = new DocumentPaneResizingPanel(); newPanel.Orientation = requestedOrientation; //replace relative pane in its' container panel //with this new panel int indexofRelativePane = relativePaneContainer.Children.IndexOf(relativePane); relativePaneContainer.Children.Remove(relativePane); relativePaneContainer.Children.Insert(indexofRelativePane, newPanel); //now we have a panel correctly placed in the tree newPanel.Children.Add(relativePane); //use InsertChildRelativeTo function to add a resizingsplitter between //the two children newPanel.InsertChildRelativeTo( paneToAnchor, relativePane, anchor == AnchorStyle.Right || anchor == AnchorStyle.Bottom); relativePaneContainer = newPanel; } else { if (anchor == AnchorStyle.Left || anchor == AnchorStyle.Top) { //add new child before first (prepend) relativePaneContainer.InsertChildRelativeTo(paneToAnchor, relativePane, false); } else { //add new child after last (append) relativePaneContainer.InsertChildRelativeTo(paneToAnchor, relativePane, true); } } } #endregion paneToAnchor.Focus(); (paneToAnchor.SelectedItem as ManagedContent).SetAsActive(); if (paneToAnchor.SelectedItem is DocumentContent) ActiveDocument = paneToAnchor.SelectedItem as DocumentContent; } /// <summary> /// Anchor a dockable pane (<see cref="DockablePane"/>) to a border of an other dockable pane /// </summary> /// <param name="paneToAnchor">Pane to anchor</param> /// <param name="relativePane">Pane relative</param> /// <param name="anchor"></param> public void Anchor(DockablePane paneToAnchor, DockablePane relativePane, AnchorStyle anchor) { if (anchor == AnchorStyle.None) anchor = AnchorStyle.Right; //get a refernce to the resizingpanel container of relativePane ResizingPanel relativePaneContainer = LogicalTreeHelper.GetParent(relativePane) as ResizingPanel; Orientation requestedOrientation = (anchor == AnchorStyle.Bottom || anchor == AnchorStyle.Top) ? Orientation.Vertical : Orientation.Horizontal; if (relativePaneContainer == null) { Debug.Assert(relativePane.Parent == this); relativePaneContainer = new ResizingPanel(); relativePaneContainer.Orientation = requestedOrientation; this.Content = relativePaneContainer; relativePaneContainer.Children.Add(relativePane); } Debug.Assert(relativePaneContainer != null, "By now we can't have a pane without a resizing panel containing it"); #region Create and setup container panel if (relativePaneContainer != null) { //check if orientation is right if (relativePaneContainer.Orientation != requestedOrientation) { //if the existing panel is not oriented as we want //create a new one ResizingPanel newPanel = new ResizingPanel(); newPanel.Orientation = requestedOrientation; if (newPanel.Orientation == Orientation.Horizontal) ResizingPanel.SetResizeHeight(newPanel, ResizingPanel.GetResizeHeight(relativePane)); else ResizingPanel.SetResizeWidth(newPanel, ResizingPanel.GetResizeWidth(relativePane)); //replace relative pane in its' container panel //with this new panel int indexofRelativePane = relativePaneContainer.Children.IndexOf(relativePane); relativePaneContainer.Children.Remove(relativePane); relativePaneContainer.Children.Insert(indexofRelativePane, newPanel); //now we have a panel correctly placed in the tree newPanel.Children.Add(relativePane); newPanel.InsertChildRelativeTo( paneToAnchor, relativePane, anchor == AnchorStyle.Right || anchor == AnchorStyle.Bottom); relativePaneContainer = newPanel; } else { if (anchor == AnchorStyle.Left || anchor == AnchorStyle.Top) { //add new child before first (prepend) relativePaneContainer.InsertChildRelativeTo(paneToAnchor, relativePane, false); } else { //add new child after last (append) relativePaneContainer.InsertChildRelativeTo(paneToAnchor, relativePane, true); } } } #endregion //than set the new anchor style for the pane paneToAnchor.Anchor = relativePane.Anchor; if (anchor == AnchorStyle.Left || anchor == AnchorStyle.Right) { double w = Math.Min( ResizingPanel.GetEffectiveSize(relativePane).Width / 2.0, ResizingPanel.GetEffectiveSize(paneToAnchor).Width); ResizingPanel.SetResizeWidth(paneToAnchor, new GridLength(w, GridUnitType.Pixel)); ResizingPanel.SetResizeHeight(paneToAnchor, new GridLength(1.0, GridUnitType.Star)); } else { double h = Math.Min( ResizingPanel.GetEffectiveSize(relativePane).Height / 2.0, ResizingPanel.GetEffectiveSize(paneToAnchor).Height); ResizingPanel.SetResizeWidth(paneToAnchor, new GridLength(1.0, GridUnitType.Star)); ResizingPanel.SetResizeHeight(paneToAnchor, new GridLength(h, GridUnitType.Pixel)); } //refresh contents state foreach (DockableContent draggedContent in paneToAnchor.Items) { draggedContent.SetStateToDock(); } if (relativePaneContainer != null) relativePaneContainer.AdjustPanelSizes(); paneToAnchor.Focus(); } public void DropInto(Pane paneDragged, Pane paneToDropInto) { if (paneDragged is DockablePane && paneToDropInto is DockablePane) DropInto(paneDragged as DockablePane, paneToDropInto as DockablePane); else if (paneDragged is DockablePane && paneToDropInto is DocumentPane) DropInto(paneDragged as DockablePane, paneToDropInto as DocumentPane); else if (paneDragged is DocumentPane && paneToDropInto is DocumentPane) DropInto(paneDragged as DocumentPane, paneToDropInto as DocumentPane); else Debug.Assert(false); } public void DropInto(DocumentPane paneDragged, DocumentPane paneToDropInto) { //transfer tha contents of dragged pane (conatined in a FloatingWindow) //to the pane which user select ManagedContent contentToFocus = null; while (paneDragged.Items.Count > 0) { ManagedContent contentToTransfer = paneDragged.RemoveContent(0); paneToDropInto.Items.Insert(0, contentToTransfer); contentToFocus = contentToTransfer; } paneToDropInto.SelectedIndex = 0; paneToDropInto.Focus(); if (contentToFocus != null) contentToFocus.SetAsActive(); } public void DropInto(DockablePane paneDragged, DocumentPane paneToDropInto) { if (paneToDropInto != MainDocumentPane) paneToDropInto = MainDocumentPane; //transfer contents of dragged pane (contained in a FloatingWindow) //to the pane which user select, taking care of setting contents state //to Dock (using Dock() method of class DockablePane). while (paneDragged.Items.Count > 0) { ManagedContent contentToTransfer = paneDragged.RemoveContent(0); paneToDropInto.Items.Add(contentToTransfer); DockableContent dockContentToTransfer = contentToTransfer as DockableContent; if (dockContentToTransfer != null) dockContentToTransfer.SetStateToDocument(); } paneToDropInto.SelectedIndex = paneToDropInto.Items.Count - 1; paneToDropInto.Focus(); } public void DropInto(DockablePane paneDragged, DockablePane paneToDropInto) { //transfer tha contents of dragged pane (conatined in a FloatingWindow) //to the pane which user select, taking care of setting contents state //to Dock (using Dock() method of class DockablePane). while (paneDragged.Items.Count > 0) { ManagedContent contentToTransfer = paneDragged.RemoveContent(0); paneToDropInto.Items.Add(contentToTransfer); DockableContent dockContentToTransfer = contentToTransfer as DockableContent; if (dockContentToTransfer != null) dockContentToTransfer.SetStateToDock(); } paneToDropInto.SelectedIndex = paneToDropInto.Items.Count - 1; paneToDropInto.Focus(); } bool RemoveContentFromTabGroup(DockableContent contentToRemove) { foreach (Panel anchorTabPanel in _anchorTabPanels) { foreach (DockablePaneAnchorTabGroup group in anchorTabPanel.Children) { foreach (DockablePaneAnchorTab tab in group.Children) { if (tab.ReferencedContent == contentToRemove) { group.Children.Remove(tab); if (group.Children.Count == 0) anchorTabPanel.Children.Remove(group); return true; } } } } return false; } /// <summary> /// Remove a pane from border tab groups /// </summary> /// <param name="pane">Pane to remove</param> /// <returns>True if pane was removed, false otherwise</returns> bool RemovePaneFromTabGroups(DockablePane paneToRemove) { foreach (Panel anchorTabPanel in _anchorTabPanels) { foreach (DockablePaneAnchorTabGroup group in anchorTabPanel.Children) { if (group.ReferencedPane == paneToRemove) { //foreach (DockablePaneAnchorTab tab in group.Children) //{ // tab.ReferencedContent.Icon = tab.Icon; // tab.Icon = null; //} anchorTabPanel.Children.Remove(group); return true; } } } return false; } /// <summary> /// Autohides/redock a dockable pane /// </summary> /// <param name="pane">Pane to auto hide/redock</param> public void ToggleAutoHide(DockablePane pane) { if (!_OnApplyTemplateFlag) { Debug.WriteLine("Layout has been restored before creating DockingManager object: force WPF to apply the template..."); ApplyTemplate(); } //if pane is in auto hide state then is found //referenced by a DockablePaneAnchorTabGroup //if so redock it in its original position if (RemovePaneFromTabGroups(pane)) { #region Pane is present in tab anchor panels DockableContent selectedContent = _flyoutWindow != null && _flyoutWindow.ReferencedPane != null && _flyoutWindow.ReferencedPane.Items.Count > 0 ? _flyoutWindow.ReferencedPane.Items[0] as DockableContent : pane.Items[0] as DockableContent; HideAutoHideWindow(); ResizingPanel parentPanel = pane.Parent as ResizingPanel; if (parentPanel != null && parentPanel.Children.Count >= 3) { parentPanel.AdjustPanelSizes(); } //reset content state to docked foreach (DockableContent content in pane.Items) { content.SetStateToDock(); } pane.Focus(); pane.SelectedItem = selectedContent; ActiveContent = selectedContent; #endregion } else { #region Pane is not auto hidden //Create e new group DockablePaneAnchorTabGroup group = new DockablePaneAnchorTabGroup(); //associate it to the pane group.ReferencedPane = pane; DockableContent selectedContent = pane.SelectedItem as DockableContent; //add contents to it foreach (DockableContent content in pane.Items) { DockablePaneAnchorTab tab = new DockablePaneAnchorTab(); tab.ReferencedContent = content; tab.Anchor = pane.Anchor; tab.Icon = content.Icon; group.Children.Add(tab); content.SetStateToAutoHide(); } //place group under correct anchor tabpanel switch (pane.Anchor) { case AnchorStyle.Left: if (_leftAnchorTabPanel != null) _leftAnchorTabPanel.Children.Add(group); break; case AnchorStyle.Top: if (_topAnchorTabPanel != null) _topAnchorTabPanel.Children.Add(group); break; case AnchorStyle.Right: if (_rightAnchorTabPanel != null) _rightAnchorTabPanel.Children.Add(group); break; case AnchorStyle.Bottom: if (_bottomAnchorTabPanel != null) _bottomAnchorTabPanel.Children.Add(group); break; } #endregion } //refresh arrangements traversing bottom-up visual tree FrameworkElement parentElement = pane.Parent as FrameworkElement; while (parentElement != null) { parentElement.InvalidateMeasure(); parentElement = parentElement.Parent as FrameworkElement; } } #endregion #region Hide/Show contents List<DockableContent> _hiddenContents = new List<DockableContent>(); #if DEBUG internal void CheckHiddenState(DockableContent contentToCheck) { if (contentToCheck.State == DockableContentState.Hidden) Debug.Assert(_hiddenContents.Contains(contentToCheck)); else Debug.Assert(!_hiddenContents.Contains(contentToCheck)); } #endif /// <summary> /// Hide a dockable content removing it from its container <see cref="Pane"/> /// </summary> /// <param name="content">Content to hide</param> /// <remarks>Note that if you simply remove a content from its container without calling this method, the /// layout serializer component can't managed correctly the removed content.</remarks> public void Hide(DockableContent content) { if (content.State == DockableContentState.Hidden) return; + if (!content.IsCloseable) + return; + content.SaveCurrentStateAndPosition(); if (content.State == DockableContentState.AutoHide) { HideAutoHideWindow(); RemoveContentFromTabGroup(content); } if (content.State == DockableContentState.FloatingWindow || content.State == DockableContentState.DockableWindow) { DockableFloatingWindow floatingWindow = Window.GetWindow(content) as DockableFloatingWindow; if (floatingWindow != null && floatingWindow.HostedPane.HasSingleItem) { floatingWindow.Close(); } content.DetachFromContainerPane(); } else { content.DetachFromContainerPane(); } if (content.State != DockableContentState.Hidden) { content.SetStateToHidden(); Debug.Assert(!_hiddenContents.Contains(content)); _hiddenContents.Add(content); } if (ActiveDocument == content) ActiveDocument = null; if (ActiveContent == content) ActiveContent = null; } /// <summary> /// Show or add a document in AvalonDock /// </summary> /// <param name="document">Document to show/add.</param> /// <remarks>If document provided is not present in the <see cref="Documents"/> list, this method inserts it in first position of <see cref="MainDocumentPane.Items"/> collection. /// In both cases select it in the container <see cref="DocumentPane"/>.</remarks> public void Show(DocumentContent document) { bool found = false; foreach (DocumentContent doc in Documents) { if (doc == document) { found = true; break; } } if (!found && MainDocumentPane != null) { if (document.Parent is DocumentPane) { ((DocumentPane)document.Parent).Items.Clear(); } //if (document.Parent != null) //{ // throw new InvalidProgramException( // string.Format("Disconnnect first the document from its logical parent ({0})", // document.Parent.GetType())); //} MainDocumentPane.Items.Insert(0, document); } //DocumentPane docPane = document.ContainerPane as DocumentPane; //if (docPane != null) //{ // docPane.SelectedItem = document; // if (document.Content is IInputElement) // Keyboard.Focus(document.Content as IInputElement); //} document.SetAsActive(); } /// <summary> /// Show a dockable content in its container <see cref="Pane"/> /// </summary> /// <param name="content">Content to show</param> public void Show(DockableContent content) { Show(content, DockableContentState.Docked); } /// <summary> /// Show a dockable content in its container with a desidered state /// </summary> /// <param name="content">Content to show</param> /// <param name="desideredState">State desidered</param> public void Show(DockableContent content, DockableContentState desideredState) { Show(content, desideredState, AnchorStyle.None); } /// <summary> /// Show a dockable content in its container with a desidered state /// </summary> /// <param name="content">Content to show</param> /// <param name="desideredState">State desidered</param> /// <param name="desideredAnchor">Border to which anchor the newly created container pane</param> /// <remarks></remarks> public void Show(DockableContent content, DockableContentState desideredState, AnchorStyle desideredAnchor) { #region Dockable content if (desideredState == DockableContentState.Hidden)//??!!show hidden? Hide(content); if (content.State == DockableContentState.AutoHide) { ShowFlyoutWindow(content); } else if (content.State == DockableContentState.Docked || content.State == DockableContentState.Document) { if (content.ContainerPane == null) { //Problem!? try to rescue if (content.State == DockableContentState.Docked) { //find the the pane which the desidered anchor style DockablePane foundPane = this.FindChildDockablePane(desideredAnchor); if (foundPane != null) foundPane.Items.Add(content); else { //if no suitable pane was found create e new one on the fly DockablePane pane = new DockablePane(); pane.Items.Add(content); Anchor(pane, desideredAnchor); } } else { //add to main document pane MainDocumentPane.Items.Add(content); } } if (content.ContainerPane.GetManager() == null) { //disconnect the parent pane from previous panel //((Panel)content.ContainerPane.Parent).Children.Remove(content.ContainerPane); if (content.ContainerPane.Parent != null) { ((Panel)content.ContainerPane.Parent).Children.Remove(content.ContainerPane); } Anchor(content.ContainerPane, desideredAnchor); } if (desideredState == DockableContentState.DockableWindow || desideredState == DockableContentState.FloatingWindow) { DockableFloatingWindow floatingWindow = new DockableFloatingWindow(this, content); floatingWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner; floatingWindow.Owner = Window.GetWindow(this); //if (content.Content != null) //{ // floatingWindow.Width = Math.Min(((FrameworkElement)content.Content).ActualWidth, ResizingPanel.GetResizeWidth(content.ContainerPane)); // floatingWindow.Height = Math.Min(((FrameworkElement)content.Content).ActualHeight, ResizingPanel.GetResizeHeight(content.ContainerPane)); //} //else //{ floatingWindow.Width = 400; floatingWindow.Height = 400; //} RegisterFloatingWindow(floatingWindow); floatingWindow.Show(); } else if (desideredState == DockableContentState.AutoHide) { if (content.ContainerPane != null) content.ContainerPane.SelectedItem = this; //content.FocusContent(); //if (content.Content is IInputElement) // Keyboard.Focus(content.Content as IInputElement); content.SetAsActive(); DockablePane.ToggleAutoHideCommand.Execute(null, content.ContainerPane); } else if (desideredState == DockableContentState.Document) { DocumentPane docPane = MainDocumentPane; if (docPane != null) { docPane.Items.Add(content.DetachFromContainerPane()); docPane.SelectedItem = content; content.SetStateToDocument(); } } else { content.ContainerPane.SelectedItem = content; content.SetAsActive(); DockablePane dockParent = content.ContainerPane as DockablePane; if (content.ActualWidth == 0.0 && ( dockParent.Anchor == AnchorStyle.Left || dockParent.Anchor == AnchorStyle.Right)) { ResizingPanel.SetResizeWidth(dockParent, new GridLength(200)); ResizingPanel.SetEffectiveSize(dockParent, new Size(200, 0.0)); } else if (content.ActualWidth == 0.0 && ( dockParent.Anchor == AnchorStyle.Left || dockParent.Anchor == AnchorStyle.Right)) { ResizingPanel.SetResizeWidth(dockParent, new GridLength(200)); ResizingPanel.SetEffectiveSize(dockParent, new Size(200, 0.0)); } //ActiveContent = content; ////content.FocusContent(); //if (content.Content is IInputElement) // Keyboard.Focus(content.Content as IInputElement); } } else if ( content.State == DockableContentState.DockableWindow || content.State == DockableContentState.FloatingWindow) { FloatingDockablePane containerPane = content.ContainerPane as FloatingDockablePane; if (containerPane != null) { //check if visible on the primary screen if (containerPane.FloatingWindow.Left > System.Windows.SystemParameters.PrimaryScreenWidth) containerPane.FloatingWindow.Left = System.Windows.SystemParameters.PrimaryScreenWidth - containerPane.FloatingWindow.Width; if (containerPane.FloatingWindow.Top > System.Windows.SystemParameters.PrimaryScreenHeight) containerPane.FloatingWindow.Top = System.Windows.SystemParameters.PrimaryScreenHeight - containerPane.FloatingWindow.Height; containerPane.FloatingWindow.Activate(); } } else if (content.State == DockableContentState.Document) { if (content.ContainerPane != null) content.ContainerPane.SelectedItem = this; //content.FocusContent(); //if (content.Content is IInputElement) // Keyboard.Focus(content.Content as IInputElement); content.SetAsActive(); } else if (content.State == DockableContentState.Hidden) { Debug.Assert(_hiddenContents.Contains(content)); _hiddenContents.Remove(content); if (desideredState == DockableContentState.Docked || desideredState == DockableContentState.AutoHide) { if (content.SavedStateAndPosition != null && content.SavedStateAndPosition.ContainerPane != null && content.SavedStateAndPosition.ChildIndex >= 0 && content.SavedStateAndPosition.ContainerPane.GetManager() == this && desideredState == DockableContentState.Docked) { //ok previous container pane is here.. Pane prevPane = content.SavedStateAndPosition.ContainerPane; if (content.SavedStateAndPosition.ChildIndex < prevPane.Items.Count) { prevPane.Items.Insert(content.SavedStateAndPosition.ChildIndex, content); } else { prevPane.Items.Add(content); } prevPane.SelectedItem = content; content.SetStateToDock(); } else { DockablePane newHostpane = new DockablePane(); newHostpane.Items.Add(content); if (desideredAnchor == AnchorStyle.None && content.SavedStateAndPosition != null && content.SavedStateAndPosition.Anchor != AnchorStyle.None) desideredAnchor = content.SavedStateAndPosition.Anchor; if (desideredAnchor == AnchorStyle.None) desideredAnchor = AnchorStyle.Right; if (desideredAnchor == AnchorStyle.Left || desideredAnchor == AnchorStyle.Right) { double w = 200; if (content.SavedStateAndPosition != null && !double.IsInfinity(content.SavedStateAndPosition.Width) && !double.IsNaN(content.SavedStateAndPosition.Width)) w = content.SavedStateAndPosition.Width; ResizingPanel.SetResizeWidth(newHostpane, new GridLength(w)); ResizingPanel.SetEffectiveSize(newHostpane, new Size(w, 0.0)); } else { double h = 200; if (content.SavedStateAndPosition != null && !double.IsInfinity(content.SavedStateAndPosition.Height) && !double.IsNaN(content.SavedStateAndPosition.Height)) h = content.SavedStateAndPosition.Height; ResizingPanel.SetResizeHeight(newHostpane, new GridLength(h)); ResizingPanel.SetEffectiveSize(newHostpane, new Size(0.0, h)); } Anchor(newHostpane, desideredAnchor); if (desideredState == DockableContentState.AutoHide) { DockablePane.ToggleAutoHideCommand.Execute(null, newHostpane); } } ActiveContent = content; } else if (desideredState == DockableContentState.DockableWindow || desideredState == DockableContentState.FloatingWindow) { DockablePane newHostpane = new DockablePane(); newHostpane.Items.Add(content); content.SetStateToDock(); //ResizingPanel.SetResizeWidth(newHostpane, 200); //ResizingPanel.SetResizeWidth(newHostpane, 500); DockableFloatingWindow floatingWindow = new DockableFloatingWindow(this, newHostpane); floatingWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner; floatingWindow.Width = 200; floatingWindow.Height = 500; floatingWindow.Owner = Window.GetWindow(this); RegisterFloatingWindow(floatingWindow); floatingWindow.Show(); } else if (desideredState == DockableContentState.Document) { DocumentPane docPane = MainDocumentPane; if (docPane != null) { docPane.Items.Add(content); docPane.SelectedItem = content; content.SetStateToDocument(); } } } #endregion #if DEBUG CheckHiddenState(content); #endif } #endregion #region Anchor Style Update routines protected override Size ArrangeOverride(Size arrangeBounds) { //at the moment this is the easy way to get anchor properties always updated if (this.Content as ResizingPanel != null) UpdateAnchorStyle(); return base.ArrangeOverride(arrangeBounds); } internal void UpdateAnchorStyle() { ResizingPanel mainPanel = this.Content as ResizingPanel; Debug.Assert(mainPanel != null); UpdateAnchorStyle(mainPanel); } /// <summary> /// Update the <see cref="DockablePane.Anchor"/> property relative to the <see cref="DocumentContent"/> object /// </summary> /// <param name="panel"></param> /// <returns></returns> /// <remarks>Traverse the logical tree starting from root <see cref="ResizingPanel"/> and set property <see cref="DockablePane.Anchor"/> of dockable pane found.</remarks> void UpdateAnchorStyle(ResizingPanel panel) { AnchorStyle currentAnchor = panel.Orientation == Orientation.Horizontal ? AnchorStyle.Left : AnchorStyle.Top; bool foundDocumentContent = false; foreach (FrameworkElement child in panel.Children) { if (child is ResizingPanel) { if (!foundDocumentContent && GetMainDocumentPane(child as ResizingPanel) != null) { foundDocumentContent = true; currentAnchor = panel.Orientation == Orientation.Horizontal ? AnchorStyle.Right : AnchorStyle.Bottom; UpdateAnchorStyle(child as ResizingPanel); } else ForceAnchorStyle(child as ResizingPanel, currentAnchor); } else if (child is DocumentPane) { foundDocumentContent = true; currentAnchor = panel.Orientation == Orientation.Horizontal ? AnchorStyle.Right : AnchorStyle.Bottom; } else if (child is DockablePane) { (child as DockablePane).Anchor = currentAnchor; } } } /// <summary> /// Called by <see cref="UpdateAnchorStyle"/> whene a <see cref="DocumentContent"/> object has been found /// </summary> /// <param name="panel"></param> /// <param name="forcedAnchor"></param> void ForceAnchorStyle(ResizingPanel panel, AnchorStyle forcedAnchor) { foreach (FrameworkElement child in panel.Children) { if (child is ResizingPanel) { ForceAnchorStyle((child as ResizingPanel), forcedAnchor); } else if ((child is DockablePane)) { ((DockablePane)child).Anchor = forcedAnchor; } } } #endregion #region Flyout window FlyoutPaneWindow _flyoutWindow = null; WindowInteropWrapper _wndInteropWrapper = null; void HideAutoHideWindow() { if (_flyoutWindow != null) { _flyoutWindow.Height = 0.0; _flyoutWindow.Width = 0.0; _flyoutWindow.Close(); _flyoutWindow = null; } } internal void ShowFlyoutWindow(DockableContent content) { //check if parent window is Active Window parentWindow = Window.GetWindow(this); if (parentWindow == null) return; if (!parentWindow.IsActive && (_flyoutWindow == null || !_flyoutWindow.IsActive)) return; //check if content is already visible in a flyout window if (_flyoutWindow != null && _flyoutWindow.ReferencedPane.Items.Contains(content)) return; //hide previous create window HideAutoHideWindow(); //select this content in the referenced pane content.ContainerPane.SelectedItem = content; if (_wndInteropWrapper == null) { _wndInteropWrapper = new WindowInteropWrapper(); _wndInteropWrapper.OnWindowPosChanging+=new EventHandler(_wndInteropWrapper_OnWindowPosChanging); } _wndInteropWrapper.AttachedObject = parentWindow; //create e new window _flyoutWindow = new FlyoutPaneWindow(this, content); _flyoutWindow.Owner = parentWindow; _flyoutWindow.FlowDirection = this.FlowDirection; UpdateFlyoutWindowPosition(true); _flyoutWindow.Closing += new System.ComponentModel.CancelEventHandler(_flyoutWindow_Closing); _flyoutWindow.Show(); @@ -2204,960 +2207,969 @@ namespace AvalonDock { if (!_flyoutWindow.IsOpening && !_flyoutWindow.IsClosing) _flyoutWindow.Left = FlowDirection == FlowDirection.RightToLeft ? locDockingManager.X + this.ActualWidth - rightTabsWidth - _flyoutWindow.Width : locDockingManager.X + leftTabsWidth; } } if (_flyoutWindow.ReferencedPane.Anchor == AnchorStyle.Top) { _flyoutWindow.Left = locDockingManager.X + leftTabsWidth; _flyoutWindow.Width = this.ActualWidth - rightTabsWidth -leftTabsWidth; _flyoutWindow.MaxWidth = ActualWidth; _flyoutWindow.MaxHeight = ActualHeight - topTabsHeight; if (initialSetup) { _flyoutWindow.Height = 0.0; _flyoutWindow.TargetHeight = resHeight; } else { if (!_flyoutWindow.IsOpening && !_flyoutWindow.IsClosing) _flyoutWindow.Top = locDockingManager.Y + topTabsHeight; } } if (_flyoutWindow.ReferencedPane.Anchor == AnchorStyle.Bottom) { _flyoutWindow.Left = locDockingManager.X + leftTabsWidth; _flyoutWindow.Width = this.ActualWidth - rightTabsWidth - leftTabsWidth; _flyoutWindow.MaxWidth = ActualWidth; _flyoutWindow.MaxHeight = ActualHeight - bottomTabsHeight; if (initialSetup) { _flyoutWindow.Top = locDockingManager.Y + this.ActualHeight - bottomTabsHeight; _flyoutWindow.Height = 0.0; _flyoutWindow.TargetHeight = resHeight; } else { if (!_flyoutWindow.IsOpening && !_flyoutWindow.IsClosing) _flyoutWindow.Top = locDockingManager.Y + this.ActualHeight - bottomTabsHeight - _flyoutWindow.Height; if (_flyoutWindow.IsClosing) _flyoutWindow.Top = locDockingManager.Y + this.ActualHeight - bottomTabsHeight - _flyoutWindow.Height; } } if (_flyoutWindow != null && !_flyoutWindow.IsClosing) _flyoutWindow.UpdateClipRegion(); } void _wndInteropWrapper_OnWindowPosChanging(object sender, EventArgs e) { UpdateFlyoutWindowPosition(); } #endregion #region DragDrop Operations /// <summary> /// Begins dragging operations /// </summary> /// <param name="floatingWindow">Floating window containing pane which is dragged by user</param> /// <param name="point">Current mouse position</param> /// <param name="offset">Offset to be use to set floating window screen position</param> /// <returns>Retruns True is drag is completed, false otherwise</returns> internal bool Drag(FloatingWindow floatingWindow, Point point, Point offset) { bool mouseCaptured = IsMouseCaptured; if (!mouseCaptured) mouseCaptured = CaptureMouse(); if (mouseCaptured) { floatingWindow.Owner = Window.GetWindow(this); DragPaneServices.StartDrag(floatingWindow, point, offset); return true; } return false; } internal void Drag(DocumentContent documentContent, Point point, Point offset) { if (CaptureMouse()) { DocumentFloatingWindow floatingWindow = new DocumentFloatingWindow(this, documentContent); Drag(floatingWindow, point, offset); } } internal void Drag(DockableContent dockableContent, Point point, Point offset) { if (CaptureMouse()) { DockableFloatingWindow floatingWindow = new DockableFloatingWindow(this, dockableContent); floatingWindow.Owner = Window.GetWindow(this); RegisterFloatingWindow(floatingWindow); Drag(floatingWindow, point, offset); } } internal void Drag(DockablePane dockablePane, Point point, Point offset) { if (CaptureMouse()) { DockableFloatingWindow floatingWindow = new DockableFloatingWindow(this, dockablePane); floatingWindow.Owner = Window.GetWindow(this); RegisterFloatingWindow(floatingWindow); Drag(floatingWindow, point, offset); } } protected override void OnMouseMove(MouseEventArgs e) { if (IsMouseCaptured) { DragPaneServices.MoveDrag(this.PointToScreenDPI(e.GetPosition(this))); if (_flyoutWindow != null) _flyoutWindow.UpdateClipRegion(); } base.OnMouseMove(e); } protected override void OnMouseUp(MouseButtonEventArgs e) { CompleteDragging(e.GetPosition(this)); base.OnMouseUp(e); } protected override void OnMouseLeave(MouseEventArgs e) { CompleteDragging(e.GetPosition(this)); base.OnMouseLeave(e); } /// <summary> /// Ends all previously initiated dragging operations /// </summary> /// <param name="ptEndDrag"></param> void CompleteDragging(Point ptEndDrag) { if (IsMouseCaptured) { DragPaneServices.EndDrag(this.PointToScreenDPI(ptEndDrag)); ReleaseMouseCapture(); } } DragPaneServices _dragPaneServices; internal DragPaneServices DragPaneServices { get { if (_dragPaneServices == null) _dragPaneServices = new DragPaneServices(this); return _dragPaneServices; } } #endregion #region IDropSurface public bool IsSurfaceVisible { get { //a DockingManager is always visible for drop a pane return true; } } /// <summary> /// Returns a rectangle where this surface is active /// </summary> public Rect SurfaceRectangle { get { if (PresentationSource.FromVisual(this) != null) return new Rect(HelperFunc.PointToScreenWithoutFlowDirection(this, new Point(0, 0)), new Size(ActualWidth, ActualHeight)); return Rect.Empty; } } /// <summary> /// Overlay window which shows docking placeholders /// </summary> OverlayWindow _overlayWindow; /// <summary> /// Returns current overlay window /// </summary> internal OverlayWindow OverlayWindow { get { if (_overlayWindow == null) _overlayWindow = new OverlayWindow(this); return _overlayWindow; } } /// <summary> /// Handles this sourface mouse entering (show current overlay window) /// </summary> /// <param name="point">Current mouse position</param> public void OnDragEnter(Point point) { if (OverlayWindow.IsVisible) return; OverlayWindow.Owner = DragPaneServices.FloatingWindow; //OverlayWindow.Left = PointToScreen(new Point(0, 0)).X; //OverlayWindow.Top = PointToScreen(new Point(0, 0)).Y; Point origPoint = HelperFunc.PointToScreenWithoutFlowDirection(this, new Point()); OverlayWindow.Left = origPoint.X; OverlayWindow.Top = origPoint.Y; OverlayWindow.Width = ActualWidth; OverlayWindow.Height = ActualHeight; OverlayWindow.Show(); } /// <summary> /// Handles mouse overing this surface /// </summary> /// <param name="point"></param> public void OnDragOver(Point point) { } /// <summary> /// Handles mouse leave event during drag (hide overlay window) /// </summary> /// <param name="point"></param> public void OnDragLeave(Point point) { OverlayWindow.Owner = null; OverlayWindow.Hide(); Window mainWindow = Window.GetWindow(this); if (mainWindow != null) mainWindow.Activate(); } /// <summary> /// Handler drop events /// </summary> /// <param name="point">Current mouse position</param> /// <returns>Returns alwasy false because this surface doesn't support direct drop</returns> public bool OnDrop(Point point) { return false; } #endregion #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion #region Persistence void SaveLayout(XmlWriter xmlWriter, DockablePane pane) { if (pane.Items.Count > 0) { xmlWriter.WriteStartElement("DockablePane"); //if (!double.IsInfinity(ResizingPanel.GetResizeWidth(pane))) // xmlWriter.WriteAttributeString("ResizeWidth", XmlConvert.ToString(ResizingPanel.GetResizeWidth(pane))); ////if (!double.IsInfinity(ResizingPanel.GetResizeHeight(pane))) // xmlWriter.WriteAttributeString("ResizeHeight", XmlConvert.ToString(ResizingPanel.GetResizeHeight(pane))); xmlWriter.WriteAttributeString("ResizeWidth", ResizingPanel.GetResizeWidth(pane).ToString()); xmlWriter.WriteAttributeString("ResizeHeight", ResizingPanel.GetResizeHeight(pane).ToString()); xmlWriter.WriteAttributeString("EffectiveSize", new SizeConverter().ConvertToInvariantString(ResizingPanel.GetEffectiveSize(pane))); xmlWriter.WriteAttributeString("Anchor", pane.Anchor.ToString()); Debug.Assert(pane.Items.Count > 0); foreach (DockableContent content in pane.Items) { SaveLayout(xmlWriter, content); } xmlWriter.WriteEndElement(); } } void SaveLayout(XmlWriter xmlWriter, DockableFloatingWindow flWindow) { xmlWriter.WriteStartElement("FloatingWindow"); xmlWriter.WriteAttributeString("IsDockableWindow", XmlConvert.ToString(flWindow.IsDockableWindow)); xmlWriter.WriteAttributeString("Top", XmlConvert.ToString(flWindow.Top)); xmlWriter.WriteAttributeString("Left", XmlConvert.ToString(flWindow.Left)); xmlWriter.WriteAttributeString("Width", XmlConvert.ToString(flWindow.Width)); xmlWriter.WriteAttributeString("Height", XmlConvert.ToString(flWindow.Height)); SaveLayout(xmlWriter, flWindow.HostedPane); xmlWriter.WriteEndElement(); } void SaveLayout(XmlWriter xmlWriter, DockableContent content) { Debug.Assert(!string.IsNullOrEmpty(content.Name), "DockableContent must have a Name to save its content.\n" + "Click Ignore to skip this element and continue with save." ); if (!string.IsNullOrEmpty(content.Name)) { xmlWriter.WriteStartElement("DockableContent"); xmlWriter.WriteAttributeString("Name", content.Name); xmlWriter.WriteAttributeString("AutoHide", XmlConvert.ToString(content.State == DockableContentState.AutoHide)); content.SaveLayout(xmlWriter); xmlWriter.WriteEndElement(); } } void SaveLayout(XmlWriter xmlWriter, DocumentPane pane) { xmlWriter.WriteStartElement("DocumentPanePlaceHolder"); foreach (ManagedContent content in pane.Items) { if (content is DockableContent) { DockableContent dockableContent = content as DockableContent; SaveLayout(xmlWriter, dockableContent); } } xmlWriter.WriteEndElement(); } void SaveLayout(XmlWriter xmlWriter, DocumentPaneResizingPanel panelToSerialize) { xmlWriter.WriteStartElement("DocumentPanePlaceHolder"); List<DockableContent> listOfFoundContents = new List<DockableContent>(); FindContents<DockableContent>(listOfFoundContents, panelToSerialize); foreach (DockableContent content in listOfFoundContents) { SaveLayout(xmlWriter, content); } xmlWriter.WriteEndElement(); } void SaveLayout(XmlWriter xmlWriter, ResizingPanel panelToSerialize) { xmlWriter.WriteStartElement("ResizingPanel"); //if (!double.IsInfinity(ResizingPanel.GetResizeWidth(panelToSerialize))) // xmlWriter.WriteAttributeString("ResizeWidth", XmlConvert.ToString(ResizingPanel.GetResizeWidth(panelToSerialize))); //if (!double.IsInfinity(ResizingPanel.GetResizeHeight(panelToSerialize))) // xmlWriter.WriteAttributeString("ResizeHeight", XmlConvert.ToString(ResizingPanel.GetResizeHeight(panelToSerialize))); xmlWriter.WriteAttributeString("ResizeWidth", ResizingPanel.GetResizeWidth(panelToSerialize).ToString()); xmlWriter.WriteAttributeString("ResizeHeight", ResizingPanel.GetResizeHeight(panelToSerialize).ToString()); xmlWriter.WriteAttributeString("EffectiveSize", new SizeConverter().ConvertToInvariantString(ResizingPanel.GetEffectiveSize(panelToSerialize))); xmlWriter.WriteAttributeString("Orientation", Convert.ToString(panelToSerialize.Orientation)); foreach (UIElement child in panelToSerialize.Children) { if (child is DockablePane) SaveLayout(xmlWriter, child as DockablePane); else if (child is DocumentPane) SaveLayout(xmlWriter, child as DocumentPane); else if (child is DocumentPaneResizingPanel) SaveLayout(xmlWriter, child as DocumentPaneResizingPanel); else if (child is ResizingPanel) SaveLayout(xmlWriter, child as ResizingPanel); } xmlWriter.WriteEndElement(); } /// <summary> /// Save layout as xml to a <see cref="TextWriter"/> /// </summary> /// <param name="textWriter">Text writter object which receive the xml text</param> /// <remarks>The writer is not closed.</remarks> public void SaveLayout(TextWriter textWriter) { XmlTextWriter sw = new XmlTextWriter(textWriter); sw.Formatting = Formatting.Indented; sw.Indentation = 4; SaveLayout(sw); } /// <summary> /// Save layout as xml to generic stream /// </summary> /// <param name="backendStream">Stream receiving the xml string</param> /// <remarks>The stream is not closed</remarks> public void SaveLayout(Stream backendStream) { XmlTextWriter sw = new XmlTextWriter(backendStream, Encoding.Default); sw.Formatting = Formatting.Indented; sw.Indentation = 4; SaveLayout(sw); } /// <summary> /// Save layout as xml text into a file /// </summary> /// <param name="filename">Path to the file</param> /// <remarks>The file is created as new or overwritten is already exist a file with same name.</remarks> public void SaveLayout(string filename) { using (FileStream stream = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite)) SaveLayout(stream); } /// <summary> /// Send layout configuration to a <see cref="XmlTextWriter"/> object /// </summary> /// <param name="sw">Object which stores the xml</param> /// <remarks>The writer is not closed.</remarks> public void SaveLayout(XmlWriter sw) { if (!_isControlLoaded) throw new InvalidOperationException("Unable to serialize docking layout while DockingManager control is unloaded"); sw.WriteStartElement("DockingManager"); if (Content is ResizingPanel) SaveLayout(sw, Content as ResizingPanel); else if (Content is DocumentPane) SaveLayout(sw, Content as DocumentPane); else if (Content is DocumentPaneResizingPanel) SaveLayout(sw, Content as DocumentPaneResizingPanel); sw.WriteStartElement("Hidden"); foreach (DockableContent content in _hiddenContents) { SaveLayout(sw, content); } sw.WriteEndElement(); sw.WriteStartElement("Windows"); foreach (DockableFloatingWindow flWindow in _floatingWindows) { SaveLayout(sw, flWindow); } sw.WriteEndElement(); sw.WriteEndElement();//dockingmanager sw.Flush(); } void DetachContentFromDockingManager(DockableContent content) { if (content.State == DockableContentState.AutoHide) { DockablePane parentContainer = content.Parent as DockablePane; if (parentContainer != null && parentContainer.Items.Count == 1) ToggleAutoHide(content.Parent as DockablePane); } if (content.State == DockableContentState.DockableWindow || content.State == DockableContentState.FloatingWindow) { DockablePane parentContainer = content.Parent as DockablePane; if (parentContainer != null && parentContainer.Items.Count == 1) { FloatingWindow floatingWindow = Window.GetWindow(content) as FloatingWindow; - floatingWindow.Close(); + floatingWindow.Close(true); } } //this content can be hidden also if was contained in closed floating window if (content.State == DockableContentState.Hidden) Show(content); content.DetachFromContainerPane(); } public delegate void DeserializationCallbackHandler(object sender, DeserializationCallbackEventArgs e); public DeserializationCallbackHandler DeserializationCallback { get; set; } void ShowAllHiddenContents() { while (_hiddenContents.Count > 0) { Debug.Assert(_hiddenContents[0].State == DockableContentState.Hidden); Show(_hiddenContents[0]); } } void RestoreDocumentPaneLayout(XmlElement childElement, out DocumentPane mainExistingDocumentPane, out DocumentPaneResizingPanel existingDocumentPanel, DockableContent[] dockableContents) { mainExistingDocumentPane = (Content is DocumentPane) ? Content as DocumentPane : GetMainDocumentPane(Content as ResizingPanel); existingDocumentPanel = mainExistingDocumentPane.GetParentDocumentPaneResizingPanel(); if (existingDocumentPanel != null) { if (existingDocumentPanel.Parent is ResizingPanel) { ((ResizingPanel)existingDocumentPanel.Parent).RemoveChild(existingDocumentPanel); } else if (existingDocumentPanel.Parent is DockingManager) { ((DockingManager)existingDocumentPanel.Parent).Content = null; } } else if (mainExistingDocumentPane != null) { if (mainExistingDocumentPane.Parent is ResizingPanel) { ((ResizingPanel)mainExistingDocumentPane.Parent).RemoveChild(mainExistingDocumentPane); } else if (mainExistingDocumentPane.Parent is DockingManager) { ((DockingManager)mainExistingDocumentPane.Parent).Content = null; } } foreach (XmlElement contentElement in childElement.ChildNodes) { if (contentElement.HasAttribute("Name")) { DockableContent foundContent = null; string contentName = contentElement.GetAttribute("Name"); foreach (DockableContent content in dockableContents) { if (content.Name == contentName) { foundContent = content; break; } } if (foundContent == null && DeserializationCallback != null) { DeserializationCallbackEventArgs e = new DeserializationCallbackEventArgs(contentName); DeserializationCallback(this, e); foundContent = e.Content; } if (foundContent != null) { DetachContentFromDockingManager(foundContent); mainExistingDocumentPane.Items.Add(foundContent); foundContent.SetStateToDocument(); //call custom layout persistence method foundContent.RestoreLayout(contentElement); } } } } ResizingPanel RestoreLayout(XmlElement panelElement, DockableContent[] dockableContents) { ResizingPanel panel = new ResizingPanel(); if (panelElement.HasAttribute("Orientation")) panel.Orientation = (Orientation)Enum.Parse(typeof(Orientation), panelElement.GetAttribute("Orientation")); foreach (XmlElement childElement in panelElement.ChildNodes) { if (childElement.Name == "ResizingPanel") { ResizingPanel childPanel = RestoreLayout(childElement, dockableContents); if (childElement.HasAttribute("ResizeWidth")) ResizingPanel.SetResizeWidth(childPanel, (GridLength)GLConverter.ConvertFromInvariantString(childElement.GetAttribute("ResizeWidth"))); if (childElement.HasAttribute("ResizeHeight")) ResizingPanel.SetResizeHeight(childPanel, (GridLength)GLConverter.ConvertFromInvariantString(childElement.GetAttribute("ResizeHeight"))); if (childElement.HasAttribute("EffectiveSize")) ResizingPanel.SetEffectiveSize(childPanel, (Size)(new SizeConverter()).ConvertFromInvariantString(childElement.GetAttribute("EffectiveSize"))); panel.Children.Add(childPanel); } #region Restore DockablePane else if (childElement.Name == "DockablePane") { DockablePane pane = new DockablePane(); if (childElement.HasAttribute("Anchor")) pane.Anchor = (AnchorStyle)Enum.Parse(typeof(AnchorStyle), childElement.GetAttribute("Anchor")); if (childElement.HasAttribute("ResizeWidth")) ResizingPanel.SetResizeWidth(pane, (GridLength)GLConverter.ConvertFromInvariantString(childElement.GetAttribute("ResizeWidth"))); if (childElement.HasAttribute("ResizeHeight")) ResizingPanel.SetResizeHeight(pane, (GridLength)GLConverter.ConvertFromInvariantString(childElement.GetAttribute("ResizeHeight"))); if (childElement.HasAttribute("EffectiveSize")) ResizingPanel.SetEffectiveSize(pane, (Size)(new SizeConverter()).ConvertFromInvariantString(childElement.GetAttribute("EffectiveSize"))); //storeWriter.WriteAttributeString( // "EffectiveSize", new SizeConverter().ConvertToInvariantString(ResizingPanel.GetEffectiveSize(ContainerPane))); bool toggleAutoHide = false; foreach (XmlElement contentElement in childElement.ChildNodes) { if (contentElement.HasAttribute("Name")) { DockableContent foundContent = null; string contentName = contentElement.GetAttribute("Name"); foreach (DockableContent content in dockableContents) { if (content.Name == contentName) { foundContent = content; break; } } if (foundContent == null && DeserializationCallback != null) { DeserializationCallbackEventArgs e = new DeserializationCallbackEventArgs(contentName); DeserializationCallback(this, e); foundContent = e.Content; } if (foundContent != null) { DetachContentFromDockingManager(foundContent); pane.Items.Add(foundContent); foundContent.SetStateToDock(); if (contentElement.HasAttribute("AutoHide") && XmlConvert.ToBoolean(contentElement.GetAttribute("AutoHide")) && pane.Items.Count == 1) toggleAutoHide = true; //call custom layout persistence method foundContent.RestoreLayout(contentElement); } } } if (pane.Items.Count > 0) { if (toggleAutoHide) ToggleAutoHide(pane); if (pane.Items.Count > 0) panel.Children.Add(pane); } } #endregion #region Restore Contents inside a DocumentPane else if (childElement.Name == "DocumentPanePlaceHolder") { DocumentPaneResizingPanel existingDocumentPanel = null; DocumentPane mainExistingDocumentPane = null; RestoreDocumentPaneLayout(childElement, out mainExistingDocumentPane, out existingDocumentPanel, dockableContents); if (existingDocumentPanel != null) { panel.Children.Add(existingDocumentPanel); } else if (mainExistingDocumentPane != null) { panel.Children.Add(mainExistingDocumentPane); } } #endregion } return panel; } public void RestoreLayout(Stream backendStream) { XmlDocument doc = new XmlDocument(); doc.Load(backendStream); RestoreLayout(doc); } public void RestoreLayout(XmlReader reader) { XmlDocument doc = new XmlDocument(); doc.Load(reader); RestoreLayout(doc); } public void RestoreLayout(string filename) { XmlDocument doc = new XmlDocument(); doc.Load(filename); RestoreLayout(doc); } public void RestoreLayout(TextReader reader) { XmlDocument doc = new XmlDocument(); doc.Load(reader); RestoreLayout(doc); } void RestoreLayout(XmlDocument doc) { if (!_isControlLoaded) throw new InvalidOperationException("Unable to deserialize a docking layout while DockingManager control is unloaded"); if (doc.DocumentElement == null || doc.DocumentElement.Name != "DockingManager") { - Debug.Assert(false, "Layout file had not a valid structure!"); - return; + Debug.Assert(false, "Layout file hasn't a valid structure!"); + throw new InvalidOperationException("Layout file had not a valid structure!"); } if (doc.DocumentElement.ChildNodes.Count != 3 || (doc.DocumentElement.ChildNodes[0].Name != "ResizingPanel" && doc.DocumentElement.ChildNodes[0].Name != "DocumentPanePlaceHolder") || doc.DocumentElement.ChildNodes[1].Name != "Hidden" || doc.DocumentElement.ChildNodes[2].Name != "Windows") { Debug.Assert(false, "Layout file hasn't a valid structure!"); - return; + throw new InvalidOperationException("Layout file hasn't a valid structure!"); } + //Hide temp windows + HideAutoHideWindow(); + HideNavigatorWindow(); + HideDocumentNavigatorWindow(); + DockableContent[] actualContents = DockableContents; - + + //show all hidden contents ShowAllHiddenContents(); //restore main panel XmlElement rootElement = doc.DocumentElement.ChildNodes[0] as XmlElement; if (rootElement.Name == "ResizingPanel") { this.Content = RestoreLayout(rootElement, actualContents); } else if (rootElement.Name == "DocumentPanePlaceHolder") { DocumentPaneResizingPanel existingDocumentPanel = null; DocumentPane mainExistingDocumentPane = null; RestoreDocumentPaneLayout(rootElement, out mainExistingDocumentPane, out existingDocumentPanel, actualContents); if (existingDocumentPanel != null) { this.Content = existingDocumentPanel; } else if (mainExistingDocumentPane != null) { this.Content = mainExistingDocumentPane; } } //restore hidden contents foreach (XmlElement hiddenContentElement in doc.DocumentElement.ChildNodes[1].ChildNodes) { foreach (DockableContent hiddenContent in actualContents) { if (hiddenContentElement.GetAttribute("Name") == hiddenContent.Name && hiddenContent.State != DockableContentState.Hidden) { Hide(hiddenContent); hiddenContent.RestoreLayout(hiddenContentElement); } } } //restore floating windows foreach (XmlElement flWindowElement in doc.DocumentElement.ChildNodes[2].ChildNodes) { + if (flWindowElement.ChildNodes.Count != 1) + continue;//handles invalid layouts structures + bool isDockableWindow = XmlConvert.ToBoolean(flWindowElement.GetAttribute("IsDockableWindow")); Point location = new Point(XmlConvert.ToDouble(flWindowElement.GetAttribute("Left")), XmlConvert.ToDouble(flWindowElement.GetAttribute("Top"))); Size size = new Size(XmlConvert.ToDouble(flWindowElement.GetAttribute("Width")), XmlConvert.ToDouble(flWindowElement.GetAttribute("Height"))); DockableFloatingWindow flWindow = new DockableFloatingWindow(this); flWindow.Left = location.X; flWindow.Top = location.Y; flWindow.Width = size.Width; flWindow.Height = size.Height; flWindow.Owner = Window.GetWindow(this); XmlElement paneElement = flWindowElement.ChildNodes[0] as XmlElement; FloatingDockablePane paneForFloatingWindow = new FloatingDockablePane(flWindow); if (paneElement.HasAttribute("ResizingWidth")) ResizingPanel.SetResizeWidth(paneForFloatingWindow, (GridLength)GLConverter.ConvertFromInvariantString(paneElement.GetAttribute("ResizeWidth"))); if (paneElement.HasAttribute("ResizingHeight")) ResizingPanel.SetResizeHeight(paneForFloatingWindow, (GridLength)GLConverter.ConvertFromInvariantString(paneElement.GetAttribute("ResizeHeight"))); paneForFloatingWindow.Anchor = (AnchorStyle)Enum.Parse(typeof(AnchorStyle), paneElement.GetAttribute("Anchor")); DockableContent contentToTransfer = null; foreach (XmlElement contentElement in paneElement.ChildNodes) { #region Find the content to transfer string contentToFindName = contentElement.GetAttribute("Name"); foreach (DockableContent content in actualContents) { if (contentToFindName == content.Name) { contentToTransfer = content; break; } } if (contentToTransfer == null && DeserializationCallback != null) { DeserializationCallbackEventArgs e = new DeserializationCallbackEventArgs(contentToFindName); DeserializationCallback(this, e); contentToTransfer = e.Content; } #endregion if (contentToTransfer != null) { DetachContentFromDockingManager(contentToTransfer); paneForFloatingWindow.Items.Add(contentToTransfer); contentToTransfer.RestoreLayout(contentElement); } } flWindow.HostedPane = paneForFloatingWindow; flWindow.IsDockableWindow = isDockableWindow; RegisterFloatingWindow(flWindow); flWindow.ApplyTemplate(); flWindow.Show(); } } /// <summary> /// Static converter used to convert GridLength from/to string /// </summary> static GridLengthConverter GLConverter = new GridLengthConverter(); #endregion #region OnClosing/OnClosedDocument events /// <summary> /// Event fired when the document is about to be closed /// </summary> public event EventHandler<CancelEventArgs> DocumentClosing; /// <summary> /// Event fired when a document has been closed /// </summary> /// <remarks>Note that when a document is closed, property like <see cref="ManagedContent.ContainerPane"/> or <see cref="ManagedContent.Manager"/> returns null.</remarks> public event EventHandler DocumentClosed; /// <summary> /// Ovveride this method to handle <see cref="DocumentClosing"/> event. /// </summary> protected virtual void OnDocumentClosing(CancelEventArgs e) { if (DocumentClosing != null && !e.Cancel) { DocumentClosing(this, e); } } /// <summary> /// Ovveride this method to handle <see cref="DocumentClosed"/> event. /// </summary> protected virtual void OnDocumentClosed() { if (DocumentClosed != null) DocumentClosed(this, EventArgs.Empty); } internal void FireDocumentClosingEvent(CancelEventArgs e) { OnDocumentClosing(e); } internal void FireDocumentClosedEvent() { OnDocumentClosed(); } public event EventHandler<RequestDocumentCloseEventArgs> RequestDocumentClose; internal bool FireRequestDocumentCloseEvent(DocumentContent doc) { bool res = false; if (RequestDocumentClose != null) { RequestDocumentCloseEventArgs args = new RequestDocumentCloseEventArgs(doc); RequestDocumentClose(this, args); res = !args.Cancel; } return res; } #endregion } } diff --git a/AvalonDock/AvalonDock/DocumentContent.cs b/AvalonDock/AvalonDock/DocumentContent.cs index 0515782..8b143ca 100644 --- a/AvalonDock/AvalonDock/DocumentContent.cs +++ b/AvalonDock/AvalonDock/DocumentContent.cs @@ -1,295 +1,298 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.ComponentModel; using System.Diagnostics; namespace AvalonDock { /// <summary> /// Represent a document which can be host by a <see cref="DocumentPane"/>. /// </summary> /// <remarks>A document is always hosted by a <see cref="DocumentPane"/> usually in the central area of <see cref="DockingManager"/>. /// It has limited dragging features becaus it can be only moved to an other <see cref="DocumentPane"/> and can't float as a separate window. /// You can access all documents within <see cref="DockingManager"/> with property <see cref="DockingManager.Documents"/>.</remarks> public class DocumentContent : ManagedContent { static DocumentContent() { //DefaultStyleKeyProperty.OverrideMetadata(typeof(DocumentContent), new FrameworkPropertyMetadata(typeof(DocumentContent))); //Control.WidthProperty.OverrideMetadata(typeof(DocumentContent), // new FrameworkPropertyMetadata(new PropertyChangedCallback(OnSizePropertyChanged), new CoerceValueCallback(CourceSizeToNaN))); //Control.HeightProperty.OverrideMetadata(typeof(DocumentContent), // new FrameworkPropertyMetadata(new PropertyChangedCallback(OnSizePropertyChanged), new CoerceValueCallback(CourceSizeToNaN))); } public DocumentContent() { base.PropertyChanged += new PropertyChangedEventHandler(DocumentContent_PropertyChanged); } DateTime _lastActivation = DateTime.MinValue; internal DateTime LastActivation { get { return _lastActivation; } } void DocumentContent_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsActiveContent") { if (IsActiveContent) _lastActivation = DateTime.Now; } } static void OnSizePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { } static object CourceSizeToNaN(DependencyObject sender, object value) { //return double.NaN; return value; } string _infoTip; /// <summary> /// Gets or sets the information text attached to the document content. /// </summary> /// <remarks>This text is usually displayed when users switch between documents and helps them to choose the right one.</remarks> public string InfoTip { get { return _infoTip; } set { _infoTip = value; NotifyPropertyChanged("InfoTip"); } } string _contentTypeDescription; /// <summary> /// Gets or sets a text which describes the type of content contained in this document. /// </summary> public string ContentTypeDescription { get { return _contentTypeDescription; } set { _contentTypeDescription = value; NotifyPropertyChanged("ContentTypeDescription"); } } bool _isFloatingAllowed; /// <summary> /// Gets or sets a value indicating if this document can float over main window (VS2010 Feature). /// </summary> public bool IsFloatingAllowed { get { return _isFloatingAllowed; } set { _isFloatingAllowed = value; NotifyPropertyChanged("IsFloatingAllowed"); } } protected override void OnDragStart(Point ptMouse, Point ptRelativeMouse) { //Manager.Drag(this, this.PointToScreenDPI(ptMouse), ptRelativeMouse); Manager.Drag(this, HelperFunc.PointToScreenWithoutFlowDirection(this, ptMouse), ptRelativeMouse); base.OnDragStart(ptMouse, ptRelativeMouse); } protected override void OnDragMouseMove(object sender, MouseEventArgs e) { base.OnDragMouseMove(sender, e); } protected override void OnDragMouseLeave(object sender, MouseEventArgs e) { base.OnDragMouseLeave(sender, e); } public override void OnApplyTemplate() { base.OnApplyTemplate(); if (DragEnabledArea != null) { DragEnabledArea.InputBindings.Add(new InputBinding(ApplicationCommands.Close, new MouseGesture(MouseAction.MiddleClick))); } } /// <summary> /// Event fired when the document is about to be closed /// </summary> public event EventHandler<CancelEventArgs> Closing; /// <summary> /// Event fired when the document has been closed /// </summary> /// <remarks>Note that when a document is closed property like <see cref="ManagedContent.ContainerPane"/> or <see cref="ManagedContent.Manager"/> returns null.</remarks> public event EventHandler Closed; /// <summary> /// Ovveride this method to handle <see cref="DocumentContent.OnClosing"/> event. /// </summary> protected virtual void OnClosing(CancelEventArgs e) { if (Closing != null && !e.Cancel) { Closing(this, e); } } /// <summary> /// Ovveride this method to handle <see cref="DocumentContent.OnClose"/> event. /// </summary> protected virtual void OnClosed() { if (Closed != null) Closed(this, EventArgs.Empty); } /// <summary> /// Close this content without notifications /// </summary> internal void InternalClose() { DocumentPane parentPane = ContainerPane as DocumentPane; DockingManager manager = Manager; if (manager != null) { if (manager.ActiveContent == this) manager.ActiveContent = null; if (manager.ActiveDocument == this) manager.ActiveDocument = null; } if (parentPane != null) { parentPane.Items.Remove(this); parentPane.CheckContentsEmpty(); } else { FloatingDockablePane floatingParentPane = ContainerPane as FloatingDockablePane; if (floatingParentPane != null) { floatingParentPane.RemoveContent(0); if (floatingParentPane.FloatingWindow != null && !floatingParentPane.FloatingWindow.IsClosing) floatingParentPane.FloatingWindow.Close(); } } } /// <summary> /// Close this document removing it from its parent container /// </summary> /// <remarks>Use this function to close a document and remove it from its parent container. Please note /// that if you simply remove it from its parent <see cref="DocumentPane"/> without call this method, events like /// <see cref="OnClosing"/>/<see cref="OnClosed"/> are not called. /// <para> /// Note:<see cref="DockableContent"/> cannot be closed: AvalonDock simply hide a <see cref="DockableContent"/> removing all the reference to it. /// </para> /// </remarks> public bool Close() { + if (!IsCloseable) + return false; + //if documents are attached to an external source via DockingManager.DocumentsSource //let application host handle the document closing by itself if (Manager.DocumentsSource != null) { return Manager.FireRequestDocumentCloseEvent(this); } CancelEventArgs e = new CancelEventArgs(false); OnClosing(e); if (e.Cancel) return false; DockingManager oldManager = Manager; if (Manager != null) Manager.FireDocumentClosingEvent(e); if (e.Cancel) return false; InternalClose(); OnClosed(); if (oldManager != null) oldManager.FireDocumentClosedEvent(); //if (Parent != null) // throw new InvalidOperationException(); Debug.Assert(Parent == null, "Parent MUST bu null after Doc is closed"); return true; } } } diff --git a/AvalonDock/AvalonDock/DocumentFloatingWindow.cs b/AvalonDock/AvalonDock/DocumentFloatingWindow.cs index bc2faad..da060da 100644 --- a/AvalonDock/AvalonDock/DocumentFloatingWindow.cs +++ b/AvalonDock/AvalonDock/DocumentFloatingWindow.cs @@ -1,362 +1,357 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.ComponentModel; using System.Windows.Markup; using System.Diagnostics; using System.Windows.Threading; using System.Windows.Media.Animation; using System.Windows.Interop; namespace AvalonDock { public class DocumentFloatingWindow : FloatingWindow { static DocumentFloatingWindow() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml DefaultStyleKeyProperty.OverrideMetadata(typeof(DocumentFloatingWindow), new FrameworkPropertyMetadata(typeof(DocumentFloatingWindow))); Window.AllowsTransparencyProperty.OverrideMetadata(typeof(DocumentFloatingWindow), new FrameworkPropertyMetadata(true)); Window.WindowStyleProperty.OverrideMetadata(typeof(DocumentFloatingWindow), new FrameworkPropertyMetadata(WindowStyle.None)); Window.ShowInTaskbarProperty.OverrideMetadata(typeof(DocumentFloatingWindow), new FrameworkPropertyMetadata(false)); } public DocumentFloatingWindow(DockingManager manager) :base(manager) { } Pane _previousPane = null; int _arrayIndexPreviousPane = -1; public DocumentFloatingWindow(DockingManager manager, DocumentContent content) : this(manager) { //create a new temporary pane FloatingDockablePane pane = new FloatingDockablePane(this); //setup window size Width = content.ContainerPane.ActualWidth; Height = content.ContainerPane.ActualHeight; //save current content position in container pane _previousPane = content.ContainerPane; _arrayIndexPreviousPane = _previousPane.Items.IndexOf(content); pane.SetValue(ResizingPanel.ResizeWidthProperty, _previousPane.GetValue(ResizingPanel.ResizeWidthProperty)); pane.SetValue(ResizingPanel.ResizeHeightProperty, _previousPane.GetValue(ResizingPanel.ResizeHeightProperty)); //remove content from container pane content.ContainerPane.RemoveContent(_arrayIndexPreviousPane); //add content to my temporary pane pane.Items.Add(content); //let templates access this pane HostedPane = pane; if (IsDocumentFloatingAllowed) { AllowsTransparency = false; WindowStyle = WindowStyle.ToolWindow; NotifyPropertyChanged("IsDocumentFloatingAllowed"); } } public bool IsDocumentFloatingAllowed { get { if (HostedPane != null && HostedPane.Items.Count > 0) return ((DocumentContent)HostedPane.Items[0]).IsFloatingAllowed; return false; } } internal override void OnEndDrag() { if (HostedPane.Items.Count > 0) { DocumentContent content = HostedPane.Items[0] as DocumentContent; if (!content.IsFloatingAllowed) { HostedPane.Items.RemoveAt(0); _previousPane.Items.Insert(_arrayIndexPreviousPane, content); _previousPane.SelectedItem = content; Close(); } else { DocumentPane originalDocumentPane = _previousPane as DocumentPane; originalDocumentPane.CheckContentsEmpty(); } } else { DocumentPane originalDocumentPane = _previousPane as DocumentPane; originalDocumentPane.CheckContentsEmpty(); Close(); } base.OnEndDrag(); } public override Pane ClonePane() { DocumentPane paneToAnchor = new DocumentPane(); ////transfer the resizing panel sizes //paneToAnchor.SetValue(ResizingPanel.ResizeWidthProperty, // HostedPane.GetValue(ResizingPanel.ResizeWidthProperty)); //paneToAnchor.SetValue(ResizingPanel.ResizeHeightProperty, // HostedPane.GetValue(ResizingPanel.ResizeHeightProperty)); ResizingPanel.SetEffectiveSize(paneToAnchor, new Size(Width, Height)); //transfer contents from hosted pane in the floating window and //the new created dockable pane while (HostedPane.Items.Count > 0) { paneToAnchor.Items.Add( HostedPane.RemoveContent(0)); } return paneToAnchor; } protected override void OnInitialized(EventArgs e) { if (IsDocumentFloatingAllowed) { if (HostedPane != null) { Content = HostedPane; } } base.OnInitialized(e); } internal override void OnShowSelectionBox() { this.Visibility = Visibility.Hidden; base.OnShowSelectionBox(); } internal override void OnHideSelectionBox() { this.Visibility = Visibility.Visible; base.OnHideSelectionBox(); } #region Commands protected override void OnExecuteCommand(object sender, ExecutedRoutedEventArgs e) { if (e.Command == TabbedDocumentCommand) { DocumentContent currentContent = HostedPane.SelectedItem as DocumentContent; _previousPane.Items.Insert(0, HostedPane.RemoveContent(HostedPane.SelectedIndex)); _previousPane.SelectedIndex = 0; if (HostedPane.Items.Count == 0) this.Close(); e.Handled = true; } else if (e.Command == CloseCommand) { DocumentContent docContent = this.HostedPane.Items[0] as DocumentContent; - if (docContent.Close()) - { - HostedPane.RemoveContent(0); - Close(); - } - e.Handled = true; + e.Handled = docContent.Close(); } base.OnExecuteCommand(sender, e); } #endregion //#region Drag //protected override IntPtr FilterMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) //{ // handled = false; // if (!IsDocumentFloatingAllowed) // return IntPtr.Zero; // switch (msg) // { // case WM_SIZE: // case WM_MOVE: // //HostedPane.ReferencedPane.SaveFloatingWindowSizeAndPosition(this); // break; // case WM_NCLBUTTONDOWN: // if (IsDockableWindow && wParam.ToInt32() == HTCAPTION) // { // short x = (short)((lParam.ToInt32() & 0xFFFF)); // short y = (short)((lParam.ToInt32() >> 16)); // Point clickPoint = this.TransformToDeviceDPI(new Point(x, y)); // Manager.Drag(this, clickPoint, new Point(clickPoint.X - Left, clickPoint.Y - Top)); // handled = true; // } // break; // case WM_NCLBUTTONDBLCLK: // if (IsDockableWindow && wParam.ToInt32() == HTCAPTION) // { // if (IsDockableWindow) // { // if (_previousPane != null) // { // if (_previousPane.GetManager() == null) // { // DockablePane newContainerPane = new DockablePane(); // newContainerPane.Items.Add(HostedPane.RemoveContent(0)); // newContainerPane.SetValue(ResizingPanel.ResizeWidthProperty, _previousPane.GetValue(ResizingPanel.ResizeWidthProperty)); // newContainerPane.SetValue(ResizingPanel.ResizeHeightProperty, _previousPane.GetValue(ResizingPanel.ResizeHeightProperty)); // Manager.Anchor(newContainerPane, ((DockablePane)_previousPane).Anchor); // } // else // { // if (_arrayIndexPreviousPane > _previousPane.Items.Count) // _arrayIndexPreviousPane = _previousPane.Items.Count; // DockableContent currentContent = HostedPane.Items[0] as DockableContent; // _previousPane.Items.Insert(_arrayIndexPreviousPane, HostedPane.RemoveContent(0)); // _previousPane.SelectedIndex = _arrayIndexPreviousPane; // currentContent.SetStateToDock(); // } // this.Close(); // } // handled = true; // } // } // break; // case WM_NCRBUTTONDOWN: // if (wParam.ToInt32() == HTCAPTION) // { // short x = (short)((lParam.ToInt32() & 0xFFFF)); // short y = (short)((lParam.ToInt32() >> 16)); // ContextMenu cxMenu = FindResource(new ComponentResourceKey(typeof(DockingManager), ContextMenuElement.FloatingWindow)) as ContextMenu; // if (cxMenu != null) // { // foreach (MenuItem menuItem in cxMenu.Items) // menuItem.CommandTarget = this; // cxMenu.Placement = PlacementMode.AbsolutePoint; // cxMenu.PlacementRectangle = new Rect(new Point(x, y), new Size(0, 0)); // cxMenu.PlacementTarget = this; // cxMenu.IsOpen = true; // } // handled = true; // } // break; // case WM_NCRBUTTONUP: // if (wParam.ToInt32() == HTCAPTION) // { // handled = true; // } // break; // } // return IntPtr.Zero; //} //#endregion protected override void Redock() { if (_previousPane != null) { if (_previousPane.GetManager() == null) { Manager.MainDocumentPane.Items.Insert(0, HostedPane.RemoveContent(0)); } else { if (_arrayIndexPreviousPane > _previousPane.Items.Count) _arrayIndexPreviousPane = _previousPane.Items.Count; _previousPane.Items.Insert(_arrayIndexPreviousPane, HostedPane.RemoveContent(0)); _previousPane.SelectedIndex = _arrayIndexPreviousPane; } this.Close(); } base.Redock(); } protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); if (e.Cancel) return; if (this.HostedPane.Items.Count > 0) { DocumentContent docContent = this.HostedPane.Items[0] as DocumentContent; if (!docContent.Close()) e.Cancel = true; else this.HostedPane.Items.Remove(docContent); } } } } diff --git a/AvalonDock/AvalonDock/FloatingWindow.cs b/AvalonDock/AvalonDock/FloatingWindow.cs index 8071ffb..4b76cee 100644 --- a/AvalonDock/AvalonDock/FloatingWindow.cs +++ b/AvalonDock/AvalonDock/FloatingWindow.cs @@ -1,418 +1,502 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.ComponentModel; using System.Windows.Markup; using System.Diagnostics; using System.Windows.Threading; using System.Windows.Media.Animation; using System.Windows.Interop; +using System.Runtime.InteropServices; namespace AvalonDock { public abstract class FloatingWindow : Window, INotifyPropertyChanged { static FloatingWindow() { Window.ShowInTaskbarProperty.OverrideMetadata(typeof(FloatingWindow), new FrameworkPropertyMetadata(false)); Window.WindowStyleProperty.OverrideMetadata(typeof(FloatingWindow), new FrameworkPropertyMetadata(WindowStyle.ToolWindow)); } public FloatingWindow() { this.Loaded += new RoutedEventHandler(OnLoaded); this.Unloaded += new RoutedEventHandler(OnUnloaded); this.SizeChanged += new SizeChangedEventHandler(FloatingWindow_SizeChanged); this.CommandBindings.Add(new CommandBinding(SetAsDockableWindowCommand, OnExecuteCommand, OnCanExecuteCommand)); this.CommandBindings.Add(new CommandBinding(SetAsFloatingWindowCommand, OnExecuteCommand, OnCanExecuteCommand)); this.CommandBindings.Add(new CommandBinding(TabbedDocumentCommand, OnExecuteCommand, OnCanExecuteCommand)); this.CommandBindings.Add(new CommandBinding(CloseCommand, OnExecuteCommand, OnCanExecuteCommand)); } void FloatingWindow_SizeChanged(object sender, SizeChangedEventArgs e) { if (HostedPane != null) { foreach (ManagedContent c in HostedPane.Items) c.FloatingWindowSize = new Size(Width, Height); ResizingPanel.SetEffectiveSize(HostedPane, new Size(Width, Height)); } } public FloatingWindow(DockingManager manager) : this() { //save manager ref _manager = manager; } DockingManager _manager = null; internal DockingManager Manager { get { return _manager; } } public FloatingDockablePane HostedPane { get { return (FloatingDockablePane)GetValue(ReferencedPaneProperty); } set { SetValue(ReferencedPaneProperty, value); } } // Using a DependencyProperty as the backing store for HostedPane. This enables animation, styling, binding, etc... public static readonly DependencyProperty ReferencedPaneProperty = DependencyProperty.Register("HostedPane", typeof(FloatingDockablePane), typeof(FlyoutPaneWindow)); internal virtual void OnEndDrag() { } internal virtual void OnShowSelectionBox() { } internal virtual void OnHideSelectionBox() { } #region Active Content Management ManagedContent lastActiveContent = null; protected override void OnActivated(EventArgs e) { if (Manager != null) { lastActiveContent = Manager.ActiveContent; Manager.ActiveContent = HostedPane.SelectedItem as ManagedContent; } base.OnActivated(e); } protected override void OnDeactivated(EventArgs e) { if (Manager != null && lastActiveContent != null) { Manager.ActiveContent = lastActiveContent; } base.OnDeactivated(e); } #endregion #region IsClosing Flag Management + public void Close(bool force) + { + ForcedClosing = force; + base.Close(); + } + + protected bool ForcedClosing { get; private set; } + + internal bool IsClosing { get; private set; } protected override void OnClosing(CancelEventArgs e) { + if (HostedPane.Items.Count > 0 && !ForcedClosing) + { + ManagedContent cntToClose = HostedPane.Items[0] as ManagedContent; + if (!cntToClose.IsCloseable) + { + e.Cancel = true; + base.OnClosing(e); + return; + } + } + IsClosing = true; base.OnClosing(e); } protected override void OnClosed(EventArgs e) { IsClosing = false; base.OnClosed(e); } #endregion public abstract Pane ClonePane(); + + #region Enable/Disable window Close Button + [DllImport("User32.dll", CharSet = CharSet.Auto)] + private static extern IntPtr GetSystemMenu( + IntPtr hWnd, + Int32 bRevert + ); + + [DllImport("User32.dll", CharSet = CharSet.Auto)] + private static extern int GetMenuItemCount( + IntPtr hMenu + ); + + [DllImport("User32.dll", CharSet = CharSet.Auto)] + private static extern int DrawMenuBar( + IntPtr hWnd + ); + + [DllImport("User32.dll", CharSet = CharSet.Auto)] + private static extern bool EnableMenuItem( + IntPtr hMenu, + Int32 uIDEnableItem, + Int32 uEnable + ); + + private const Int32 MF_BYPOSITION = 0x400; + private const Int32 MF_ENABLED = 0x0000; + private const Int32 MF_GRAYED = 0x0001; + private const Int32 MF_DISABLED = 0x0002; + + void EnableXButton() + { + WindowInteropHelper helper = new WindowInteropHelper(this); + IntPtr hMenu = GetSystemMenu(helper.Handle, 0); + + int menuItemCount = GetMenuItemCount(hMenu); + + EnableMenuItem(hMenu, menuItemCount - 1, MF_BYPOSITION | MF_ENABLED); + DrawMenuBar(helper.Handle); + } + + void DisableXButton() + { + WindowInteropHelper helper = new WindowInteropHelper(this); + IntPtr hMenu = GetSystemMenu(helper.Handle, 0); + + int menuItemCount = GetMenuItemCount(hMenu); + + EnableMenuItem(hMenu, menuItemCount - 1, MF_BYPOSITION | MF_DISABLED | MF_GRAYED); + DrawMenuBar(helper.Handle); + } + + #endregion + #region Non-Client area management protected const int WM_MOVE = 0x0003; protected const int WM_SIZE = 0x0005; protected const int WM_NCMOUSEMOVE = 0xa0; protected const int WM_NCLBUTTONDOWN = 0xA1; protected const int WM_NCLBUTTONUP = 0xA2; protected const int WM_NCLBUTTONDBLCLK = 0xA3; protected const int WM_NCRBUTTONDOWN = 0xA4; protected const int WM_NCRBUTTONUP = 0xA5; protected const int HTCAPTION = 2; protected const int SC_MOVE = 0xF010; protected const int WM_SYSCOMMAND = 0x0112; #region Load/Unload window events HwndSource _hwndSource; HwndSourceHook _wndProcHandler; protected void OnLoaded(object sender, EventArgs e) { WindowInteropHelper helper = new WindowInteropHelper(this); _hwndSource = HwndSource.FromHwnd(helper.Handle); _wndProcHandler = new HwndSourceHook(FilterMessage); _hwndSource.AddHook(_wndProcHandler); + + if (HostedPane.Items.Count > 0) + { + ManagedContent cntHosted = HostedPane.Items[0] as ManagedContent; + if (!cntHosted.IsCloseable) + { + DisableXButton(); + } + } } protected void OnUnloaded(object sender, EventArgs e) { if (_hwndSource != null) _hwndSource.RemoveHook(_wndProcHandler); } #endregion protected virtual IntPtr FilterMessage( IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled ) { handled = false; if (Manager == null) return IntPtr.Zero; switch (msg) { case WM_SIZE: case WM_MOVE: //HostedPane.ReferencedPane.SaveFloatingWindowSizeAndPosition(this); break; case WM_NCLBUTTONDOWN: if (IsDockableWindow && wParam.ToInt32() == HTCAPTION) { short x = (short)((lParam.ToInt32() & 0xFFFF)); short y = (short)((lParam.ToInt32() >> 16)); Point clickPoint = this.TransformToDeviceDPI(new Point(x, y)); Manager.Drag(this, clickPoint, new Point(clickPoint.X - Left, clickPoint.Y - Top)); handled = true; } break; case WM_NCLBUTTONDBLCLK: if (IsDockableWindow && wParam.ToInt32() == HTCAPTION) { if (IsDockableWindow) { Redock(); handled = true; } } break; case WM_NCRBUTTONDOWN: if (wParam.ToInt32() == HTCAPTION) { short x = (short)((lParam.ToInt32() & 0xFFFF)); short y = (short)((lParam.ToInt32() >> 16)); ContextMenu cxMenu = FindResource(new ComponentResourceKey(typeof(DockingManager), ContextMenuElement.FloatingWindow)) as ContextMenu; if (cxMenu != null) { foreach (MenuItem menuItem in cxMenu.Items) menuItem.CommandTarget = this; cxMenu.Placement = PlacementMode.AbsolutePoint; cxMenu.PlacementRectangle = new Rect(new Point(x, y), new Size(0, 0)); cxMenu.PlacementTarget = this; cxMenu.IsOpen = true; } handled = true; } break; case WM_NCRBUTTONUP: if (wParam.ToInt32() == HTCAPTION) { handled = true; } break; } return IntPtr.Zero; } #endregion #region Floating/dockable window state bool _dockableWindow = true; public bool IsDockableWindow { get { return _dockableWindow; } set { _dockableWindow = value; if (_dockableWindow) { foreach (ManagedContent content in HostedPane.Items) if (content is DockableContent) ((DockableContent)content).SetStateToDockableWindow(); } else { foreach (ManagedContent content in HostedPane.Items) if (content is DockableContent) ((DockableContent)content).SetStateToFloatingWindow(); } } } public bool IsFloatingWindow { get { return !IsDockableWindow; } set { IsDockableWindow = !value; } } protected virtual void Redock() { } #endregion #region Commands private static object syncRoot = new object(); private static RoutedUICommand tabbedDocumentCommand = null; public static RoutedUICommand TabbedDocumentCommand { get { lock (syncRoot) { if (null == tabbedDocumentCommand) { tabbedDocumentCommand = new RoutedUICommand("T_abbed Document", "TabbedDocument", typeof(FloatingWindow)); } } return tabbedDocumentCommand; } } private static RoutedUICommand dockableCommand = null; public static RoutedUICommand SetAsDockableWindowCommand { get { lock (syncRoot) { if (null == dockableCommand) { dockableCommand = new RoutedUICommand("D_ockable", "Dockable", typeof(FloatingWindow)); } } return dockableCommand; } } private static RoutedUICommand floatingCommand = null; public static RoutedUICommand SetAsFloatingWindowCommand { get { lock (syncRoot) { if (null == floatingCommand) { floatingCommand = new RoutedUICommand("F_loating", "Floating", typeof(FloatingWindow)); } } return floatingCommand; } } private static RoutedUICommand closeCommand = null; public static RoutedUICommand CloseCommand { get { lock (syncRoot) { if (null == closeCommand) { closeCommand = new RoutedUICommand("Close", "Close", typeof(FloatingWindow)); } } return closeCommand; } } protected virtual void OnExecuteCommand(object sender, ExecutedRoutedEventArgs e) { if (e.Command == SetAsDockableWindowCommand) { IsDockableWindow = true; e.Handled = true; } else if (e.Command == SetAsFloatingWindowCommand) { IsFloatingWindow = true; e.Handled = true; } } protected virtual void OnCanExecuteCommand(object sender, CanExecuteRoutedEventArgs e) { if (e.Command == SetAsDockableWindowCommand) e.CanExecute = IsFloatingWindow; else if (e.Command == SetAsFloatingWindowCommand) e.CanExecute = IsDockableWindow; else e.CanExecute = true; } #endregion #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion } } diff --git a/AvalonDock/AvalonDock/FlyoutPaneWindow.cs b/AvalonDock/AvalonDock/FlyoutPaneWindow.cs index f8cbc95..8651c3d 100644 --- a/AvalonDock/AvalonDock/FlyoutPaneWindow.cs +++ b/AvalonDock/AvalonDock/FlyoutPaneWindow.cs @@ -353,565 +353,571 @@ namespace AvalonDock newWidth += deltaX; } else if (CorrectedAnchor == AnchorStyle.Top) { if (newHeight + (ptMoveDrag.Y - ptStartDrag.Y) < 4.0) newHeight = 4.0; else newHeight += ptMoveDrag.Y - ptStartDrag.Y; } else if (CorrectedAnchor == AnchorStyle.Right) { if (newWidth - (deltaX) < 4) { newLeft = originalLeft + originalWidth - 4; newWidth = 4; } else { newLeft += deltaX; newWidth -= deltaX; } } else if (CorrectedAnchor == AnchorStyle.Bottom) { if (newHeight - (ptMoveDrag.Y - ptStartDrag.Y) < 4) { newTop = originalTop + originalHeight - 4; newHeight = 4; } else { newTop += ptMoveDrag.Y - ptStartDrag.Y; newHeight -= ptMoveDrag.Y - ptStartDrag.Y; } } //ResizingPanel.SetResizeHeight(ReferencedPane, ReferencedPane.ActualHeight); //ResizingPanel.SetResizeWidth(ReferencedPane, ReferencedPane.ActualWidth); Width = Math.Min(newWidth, MaxWidth); Height = Math.Min(newHeight, MaxHeight); Left = Math.Max(newLeft, MinLeft); Top = Math.Max(newTop, MinTop); ApplyRegion(new Rect(0, 0, this.Width, this.Height)); } } private void _resizer_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { UIElement dragElement = sender as UIElement; dragElement.ReleaseMouseCapture(); } #endregion #region Closing window strategies DispatcherTimer _closingTimer = null; protected override void OnMouseLeave(MouseEventArgs e) { base.OnMouseLeave(e); if (!IsFocused && !IsKeyboardFocusWithin && !ReferencedPane.IsOptionsMenuOpened) _closingTimer.Start(); } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); _closingTimer.Stop(); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); if (!IsMouseOver && !ReferencedPane.IsOptionsMenuOpened) _closingTimer.Start(); } protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e) { base.OnLostKeyboardFocus(e); if (!IsMouseOver) _closingTimer.Start(); } protected override void OnGotFocus(RoutedEventArgs e) { base.OnGotFocus(e); _closingTimer.Stop(); } protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e) { base.OnGotKeyboardFocus(e); _closingTimer.Stop(); } internal void StartCloseWindow() { _closingTimer.Start(); } void OnCloseWindow(object sender, EventArgs e) { //options menu is open don't close the flyout window if (ReferencedPane.IsOptionsMenuOpened || IsMouseDirectlyOver || (_winFormsHost != null && _winFormsHost.IsFocused && _refPane.Items.Count > 0 && ((ManagedContent)_refPane.Items[0]).IsActiveContent)) { _closingTimer.Start(); return; } _closingTimer.Stop(); if (IsClosed) return; StartCloseAnimation(); } [DllImport("user32.dll")] static extern int SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool bRedraw); [DllImport("gdi32.dll")] static extern IntPtr CreateRectRgn(int left, int top, int right, int bottom); [DllImport("gdi32.dll")] static extern int CombineRgn(IntPtr hrgnDest, IntPtr hrgnSrc1, IntPtr hrgnSrc2, int fnCombineMode); enum CombineRgnStyles : int { RGN_AND = 1, RGN_OR = 2, RGN_XOR = 3, RGN_DIFF = 4, RGN_COPY = 5, RGN_MIN = RGN_AND, RGN_MAX = RGN_COPY } public bool IsClosing { get; private set; } internal void StartCloseAnimation() { AnchorStyle CorrectedAnchor = Anchor; if (CorrectedAnchor == AnchorStyle.Left && FlowDirection == FlowDirection.RightToLeft) CorrectedAnchor = AnchorStyle.Right; else if (CorrectedAnchor == AnchorStyle.Right && FlowDirection == FlowDirection.RightToLeft) CorrectedAnchor = AnchorStyle.Left; double wnd_Width = this.ActualWidth; double wnd_Height = this.ActualHeight; double wnd_Left = this.Left; double wnd_Top = this.Top; int wnd_TrimWidth = (int)wnd_Width; int wnd_TrimHeight = (int)wnd_Height; int stepWidth = (int)(wnd_Width / 20); int stepHeight = (int)(wnd_Height / 20); DispatcherTimer animTimer = new DispatcherTimer(); animTimer.Interval = TimeSpan.FromMilliseconds(1); animTimer.Tick += (sender, eventArgs) => { bool stopTimer = false; double newLeft = 0.0; double newTop = 0.0; switch (CorrectedAnchor) { case AnchorStyle.Right: newLeft = this.Left; if (this.Left + stepWidth >= wnd_Left + wnd_Width) { newLeft = wnd_Left + wnd_Width; wnd_TrimWidth = 0; stopTimer = true; } else { newLeft += stepWidth; wnd_TrimWidth -= stepWidth; wnd_TrimWidth = Math.Max(wnd_TrimWidth, 0); } //SetWindowRgn(new WindowInteropHelper(this).Handle, CreateRectRgn(0, 0, wnd_TrimWidth, wnd_TrimHeight), true); ApplyRegion(new Rect(0, 0, wnd_TrimWidth, wnd_TrimHeight)); this.Left = newLeft; break; case AnchorStyle.Left: newLeft = this.Left; if (this.Left - stepWidth <= wnd_Left - wnd_Width) { newLeft = wnd_Left - wnd_Width; wnd_TrimWidth = 0; stopTimer = true; } else { newLeft -= stepWidth; wnd_TrimWidth -= stepWidth; wnd_TrimWidth = Math.Max(wnd_TrimWidth, 0); } this.Left = newLeft; //SetWindowRgn(new WindowInteropHelper(this).Handle, CreateRectRgn((int)(wnd_Left - this.Left), 0, (int)(wnd_Width), wnd_TrimHeight), true); ApplyRegion( new Rect((int)(wnd_Left - this.Left), 0, (int)(wnd_Width), wnd_TrimHeight)); break; case AnchorStyle.Bottom: newTop = this.Top; if (this.Top + stepHeight >= wnd_Top + wnd_Height) { newTop = wnd_Top + wnd_Height; wnd_TrimHeight = 0; stopTimer = true; } else { newTop += stepHeight; wnd_TrimHeight -= stepHeight; wnd_TrimHeight = Math.Max(wnd_TrimHeight, 0); } //SetWindowRgn(new WindowInteropHelper(this).Handle, CreateRectRgn(0, 0, wnd_TrimWidth, wnd_TrimHeight), true); ApplyRegion( new Rect(0, 0, wnd_TrimWidth, wnd_TrimHeight)); this.Top = newTop; break; case AnchorStyle.Top: newTop = this.Top; if (this.Top - stepHeight <= wnd_Top - wnd_Height) { newTop = wnd_Top - wnd_Height; wnd_TrimHeight = 0; stopTimer = true; } else { newTop -= stepHeight; wnd_TrimHeight -= stepHeight; wnd_TrimHeight = Math.Max(wnd_TrimWidth, 0); } this.Top = newTop; ApplyRegion( new Rect(0, (int)(wnd_Top - this.Top), wnd_TrimWidth, (int)(wnd_Height))); //SetWindowRgn(new WindowInteropHelper(this).Handle, CreateRectRgn(0, (int)(wnd_Top - this.Top), wnd_TrimWidth, (int)(wnd_Height)), true); break; } if (stopTimer) { //window is being closed Width = 0.0; Height = 0.0; animTimer.Stop(); if (!IsClosed) Close(); IsClosing = false; } }; IsClosing = true; animTimer.Start(); } public bool IsOpening { get; private set; } internal void StartOpenAnimation() { AnchorStyle CorrectedAnchor = Anchor; if (CorrectedAnchor == AnchorStyle.Left && FlowDirection == FlowDirection.RightToLeft) CorrectedAnchor = AnchorStyle.Right; else if (CorrectedAnchor == AnchorStyle.Right && FlowDirection == FlowDirection.RightToLeft) CorrectedAnchor = AnchorStyle.Left; double wnd_Width = this._targetWidth > 0.0 ? this._targetWidth : this.ActualWidth; double wnd_Height = this._targetHeight > 0.0 ? this._targetHeight : this.ActualHeight; double wnd_Left = this.Left; double wnd_Top = this.Top; int wnd_TrimWidth = 0; int wnd_TrimHeight = 0; int stepWidth = (int)(wnd_Width / 8); int stepHeight = (int)(wnd_Height / 8); if (CorrectedAnchor == AnchorStyle.Left) { SetWindowRgn(new WindowInteropHelper(this).Handle, CreateRectRgn(0, 0, 0, (int)wnd_Height - wnd_TrimHeight), true); this.Left = wnd_Left - wnd_Width; } else if (CorrectedAnchor == AnchorStyle.Top) { SetWindowRgn(new WindowInteropHelper(this).Handle, CreateRectRgn(0, 0, (int)wnd_Width - wnd_TrimWidth, 0), true); this.Top = wnd_Top - wnd_Height; } DispatcherTimer animTimer = new DispatcherTimer(); animTimer.Interval = TimeSpan.FromMilliseconds(2); animTimer.Tick += (sender, eventArgs) => { bool stopTimer = false; switch (CorrectedAnchor) { case AnchorStyle.Right: double newLeft = this.Left; if (this.Left - stepWidth <= wnd_Left - wnd_Width) { newLeft = wnd_Left - wnd_Width; wnd_TrimWidth = (int)wnd_Width; stopTimer = true; } else { newLeft -= stepWidth; wnd_TrimWidth += stepWidth; } //SetWindowRgn(new WindowInteropHelper(this).Handle, CreateRectRgn(0, 0, wnd_TrimWidth, (int)wnd_Height - wnd_TrimHeight), true); Width = _targetWidth; this.Left = newLeft; ApplyRegion(new Rect(0, 0, wnd_TrimWidth, (int)wnd_Height - wnd_TrimHeight)); break; case AnchorStyle.Left: if (this.Left + stepWidth >= wnd_Left) { this.Left = wnd_Left; wnd_TrimWidth = (int)wnd_Width; stopTimer = true; } else { this.Left += stepWidth; wnd_TrimWidth += stepWidth; } //SetWindowRgn(new WindowInteropHelper(this).Handle, CreateRectRgn((int)(wnd_Left - this.Left), 0, (int)(wnd_Width), (int)wnd_Height - wnd_TrimHeight), true); ApplyRegion( new Rect((int)(wnd_Left - this.Left), 0, (int)(wnd_Width), (int)wnd_Height - wnd_TrimHeight)); Width = _targetWidth; break; case AnchorStyle.Bottom: double newTop = this.Top; if (this.Top - stepHeight <= wnd_Top - wnd_Height) { newTop = wnd_Top - wnd_Height; wnd_TrimHeight = (int)wnd_Height; stopTimer = true; } else { newTop -= stepHeight; wnd_TrimHeight += stepHeight; } //SetWindowRgn(new WindowInteropHelper(this).Handle, CreateRectRgn(0, 0, (int)wnd_Width - wnd_TrimWidth, wnd_TrimHeight), true); ApplyRegion( new Rect(0, 0, (int)wnd_Width - wnd_TrimWidth, wnd_TrimHeight)); Height = _targetHeight; this.Top = newTop; break; case AnchorStyle.Top: if (this.Top + stepHeight >= wnd_Top) { this.Top = wnd_Top; wnd_TrimHeight = (int)wnd_Height; stopTimer = true; } else { this.Top += stepHeight; wnd_TrimHeight += stepHeight; } //SetWindowRgn(new WindowInteropHelper(this).Handle, CreateRectRgn(0, (int)(wnd_Top - this.Top), (int)wnd_Width - wnd_TrimWidth, (int)(wnd_Height)), true); ApplyRegion( new Rect(0, (int)(wnd_Top - this.Top), (int)wnd_Width - wnd_TrimWidth, (int)(wnd_Height))); Height = _targetHeight; break; } if (stopTimer) { //SetWindowRgn(new WindowInteropHelper(this).Handle, IntPtr.Zero, false); UpdateClipRegion(); animTimer.Stop(); IsOpening = false; } }; IsOpening = true; animTimer.Start(); } //internal void StartCloseAnimation() //{ // AnchorStyle CorrectedAnchor = Anchor; // if (CorrectedAnchor == AnchorStyle.Left && FlowDirection == FlowDirection.RightToLeft) // CorrectedAnchor = AnchorStyle.Right; // else if (CorrectedAnchor == AnchorStyle.Right && FlowDirection == FlowDirection.RightToLeft) // CorrectedAnchor = AnchorStyle.Left; // //Let closing animation to occur // //Here we get a reference to a storyboard resource with a name ClosingStoryboard and // //wait that it completes before closing the window // FrameworkElement targetElement = GetTemplateChild("INT_pane") as FrameworkElement; // if (targetElement != null) // { // Storyboard storyBoard = new Storyboard(); // if (CorrectedAnchor == AnchorStyle.Left || CorrectedAnchor == AnchorStyle.Right) // { // DoubleAnimation anim = new DoubleAnimation(this.ActualWidth, 0.0, new Duration(TimeSpan.FromMilliseconds(500))); // Storyboard.SetTargetProperty(anim, new PropertyPath("Width")); // //storyBoard.Children.Add(anim); // } // if (CorrectedAnchor == AnchorStyle.Right) // { // DoubleAnimation anim = new DoubleAnimation(this.Left, this.Left + this.ActualWidth, new Duration(TimeSpan.FromMilliseconds(500))); // Storyboard.SetTargetProperty(anim, new PropertyPath("Left")); // storyBoard.Children.Add(anim); // } // if (CorrectedAnchor == AnchorStyle.Top || CorrectedAnchor == AnchorStyle.Bottom) // { // DoubleAnimation anim = new DoubleAnimation(this.Height, 0.0, new Duration(TimeSpan.FromMilliseconds(500))); // Storyboard.SetTargetProperty(anim, new PropertyPath("Height")); // storyBoard.Children.Add(anim); // } // if (CorrectedAnchor == AnchorStyle.Bottom) // { // DoubleAnimation anim = new DoubleAnimation(this.Top, this.Top + this.Height, new Duration(TimeSpan.FromMilliseconds(500))); // Storyboard.SetTargetProperty(anim, new PropertyPath("Top")); // storyBoard.Children.Add(anim); // } // { // //DoubleAnimation anim = new DoubleAnimation(1.0, 0.0, new Duration(TimeSpan.FromMilliseconds(500))); // //Storyboard.SetTargetProperty(anim, new PropertyPath("Opacity")); // //AllowsTransparency slow down perfomance under XP/VISTA because rendering is enterely perfomed using CPU // //storyBoard.Children.Add(anim); // } // storyBoard.Completed += (animation, eventArgs) => // { // if (!IsClosed) // Close(); // }; // foreach (AnimationTimeline animTimeLine in storyBoard.Children) // { // animTimeLine.FillBehavior = FillBehavior.Stop; // } // storyBoard.Begin(this); // } //} #endregion #region Clipping Region protected override void OnActivated(EventArgs e) { if (!IsOpening && !IsClosing) UpdateClipRegion(); base.OnActivated(e); } internal void UpdateClipRegion() { //ApplyRegion(_lastApplyRect.IsEmpty ? new Rect(0, 0, this.Width, this.Height) : _lastApplyRect); ApplyRegion(new Rect(0, 0, Width, Height)); } Rect _lastApplyRect = Rect.Empty; void ApplyRegion(Rect wndRect) { - //Debug.WriteLine(wndRect); + if (!this.CanTransform()) + return; + + wndRect = new Rect( + this.TransformFromDeviceDPI(wndRect.TopLeft), + this.TransformFromDeviceDPI(wndRect.Size)); + _lastApplyRect = wndRect; if (PresentationSource.FromVisual(this) == null) return; if (_dockingManager != null) { List<Rect> otherRects = new List<Rect>(); foreach (Window fl in Window.GetWindow(_dockingManager).OwnedWindows) { //not with myself! if (fl == this) continue; if (!fl.IsVisible) continue; Rect flRect = new Rect( PointFromScreen(new Point(fl.Left, fl.Top)), PointFromScreen(new Point(fl.Left + fl.Width, fl.Top + fl.Height))); if (flRect.IntersectsWith(wndRect)) otherRects.Add(Rect.Intersect(flRect, wndRect)); } IntPtr hDestRegn = CreateRectRgn( (int)wndRect.Left, (int)wndRect.Top, (int)wndRect.Right, (int)wndRect.Bottom); foreach (Rect otherRect in otherRects) { IntPtr otherWin32Rect = CreateRectRgn( (int)otherRect.Left, (int)otherRect.Top, (int)otherRect.Right, (int)otherRect.Bottom); CombineRgn(hDestRegn, hDestRegn, otherWin32Rect, (int)CombineRgnStyles.RGN_DIFF); } SetWindowRgn(new WindowInteropHelper(this).Handle, hDestRegn, true); } } #endregion } } diff --git a/AvalonDock/AvalonDock/HelperFunc.cs b/AvalonDock/AvalonDock/HelperFunc.cs index 2a6e185..7fee730 100644 --- a/AvalonDock/AvalonDock/HelperFunc.cs +++ b/AvalonDock/AvalonDock/HelperFunc.cs @@ -1,178 +1,195 @@ using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Controls; using System.Windows.Threading; using System.Threading; namespace AvalonDock { internal static class HelperFunc { //public static bool AreVeryClose(double v1, double v2) //{ // if (Math.Abs(v1 - v2) < 0.000001) // return true; // return false; //} public static bool AreClose(double v1, double v2) { if (v1 == v2) { return true; } double num = ((Math.Abs(v1) + Math.Abs(v2)) + 10.0) * 2.2204460492503131E-16; double num2 = v1 - v2; return ((-num < num2) && (num > num2)); } public static double MultiplyCheckNaN(double v1, double v2) { //inf * 0 = 1 if (double.IsInfinity(v1) && v2 == 0.0) return 1.0; if (double.IsInfinity(v2) && v1 == 0.0) return 1.0; return v1 * v2; } public static bool IsLessThen(double v1, double v2) { if (AreClose(v1, v2)) return false; return v1 < v2; } public static Point PointToScreenWithoutFlowDirection(FrameworkElement element, Point point) { if (FrameworkElement.GetFlowDirection(element) == FlowDirection.RightToLeft) { Point leftToRightPoint = new Point( element.ActualWidth - point.X, point.Y); return element.PointToScreenDPI(leftToRightPoint); } return element.PointToScreenDPI(point); } public static T FindVisualAncestor<T>(this DependencyObject obj, bool includeThis) where T : DependencyObject { if (!includeThis) obj = VisualTreeHelper.GetParent(obj); while (obj != null && (!(obj is T))) { obj = VisualTreeHelper.GetParent(obj); } return obj as T; } public static bool IsLogicalChildContained<T>(this DependencyObject obj) where T : DependencyObject { foreach (object child in LogicalTreeHelper.GetChildren(obj)) { if (child is T) return true; if (child is DependencyObject) { bool res = (child as DependencyObject).IsLogicalChildContained<T>(); if (res) return true; } } return false; } public static T GetLogicalChildContained<T>(this DependencyObject obj) where T : DependencyObject { foreach (object child in LogicalTreeHelper.GetChildren(obj)) { if (child is T) return child as T; if (child is DependencyObject) { T childFound = (child as DependencyObject).GetLogicalChildContained<T>(); if (childFound != null) return childFound; } } return null; } public static T FindAnotherLogicalChildContained<T>(this DependencyObject obj, UIElement childToExclude) where T : DependencyObject { foreach (object child in LogicalTreeHelper.GetChildren(obj)) { if (child is T && child != childToExclude) return child as T; if (child is DependencyObject) { T childFound = (child as DependencyObject).FindAnotherLogicalChildContained<T>(childToExclude); if (childFound != null) return childFound; } } return null; } public static DockablePane FindChildDockablePane(this DockingManager manager, AnchorStyle desideredAnchor) { foreach (UIElement childObject in LogicalTreeHelper.GetChildren(manager)) { DockablePane foundPane = FindChildDockablePane(childObject, desideredAnchor); if (foundPane != null) return foundPane; } return null; } static DockablePane FindChildDockablePane(UIElement parent, AnchorStyle desideredAnchor) { if (parent is DockablePane && ((DockablePane)parent).Anchor == desideredAnchor) return parent as DockablePane; if (parent is ResizingPanel) { foreach (UIElement childObject in ((ResizingPanel)parent).Children) { DockablePane foundPane = FindChildDockablePane(childObject, desideredAnchor); if (foundPane != null) return foundPane; } } return null; } public static Point PointToScreenDPI(this Visual visual, Point pt) { Point resultPt = visual.PointToScreen(pt); return TransformToDeviceDPI(visual, resultPt); } public static Point TransformToDeviceDPI(this Visual visual, Point pt) { Matrix m = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; return new Point(pt.X / m.M11, pt.Y /m.M22); } + + public static Size TransformFromDeviceDPI(this Visual visual, Size size) + { + Matrix m = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; + return new Size(size.Width * m.M11, size.Height * m.M22); + } + + public static Point TransformFromDeviceDPI(this Visual visual, Point pt) + { + Matrix m = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; + return new Point(pt.X * m.M11, pt.Y * m.M22); + } + + public static bool CanTransform(this Visual visual) + { + return PresentationSource.FromVisual(visual) != null; + } } } diff --git a/AvalonDock/AvalonDock/ManagedContent.cs b/AvalonDock/AvalonDock/ManagedContent.cs index 514197a..03744ee 100644 --- a/AvalonDock/AvalonDock/ManagedContent.cs +++ b/AvalonDock/AvalonDock/ManagedContent.cs @@ -10,515 +10,525 @@ // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.ComponentModel; using System.Xml; using System.Windows.Forms.Integration; using System.Diagnostics; using System.Windows.Threading; using System.Threading; using System.Reflection; namespace AvalonDock { public abstract class ManagedContent : ContentControl, INotifyPropertyChanged { static ManagedContent() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml //DefaultStyleKeyProperty.OverrideMetadata(typeof(ManagedContent), new FrameworkPropertyMetadata(typeof(ManagedContent))); FocusableProperty.OverrideMetadata(typeof(ManagedContent), new FrameworkPropertyMetadata(true)); } public ManagedContent() { this.Loaded += new RoutedEventHandler(ManagedContent_Loaded); this.Unloaded += new RoutedEventHandler(ManagedContent_Unloaded); } void ManagedContent_Loaded(object sender, RoutedEventArgs e) { } void ManagedContent_Unloaded(object sender, RoutedEventArgs e) { } public string Title { get { return (string)GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } // Using a DependencyProperty as the backing store for Title. This enables animation, styling, binding, etc... public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(ManagedContent)); //public string IconSource //{ // get { return (string)GetValue(IconSourceProperty); } // set { SetValue(IconSourceProperty, value); } //} //// Using a DependencyProperty as the backing store for Icon. This enables animation, styling, binding, etc... //public static readonly DependencyProperty IconSourceProperty = // DependencyProperty.Register("IconSource", typeof(string), typeof(ManagedContent)); /// <summary> /// Access to <see cref="IconProperty"/> dependency property /// </summary> public object Icon { get { return (object)GetValue(IconProperty); } set { SetValue(IconProperty, value); } } /// <summary> /// Select an icon object for the content /// </summary> public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(object), typeof(ManagedContent), new FrameworkPropertyMetadata(null, new CoerceValueCallback(OnCoerce_Icon))); private static object OnCoerce_Icon(DependencyObject o, object value) { if (value is string) { Uri iconUri; // try to resolve given value as an absolute URI if (Uri.TryCreate(value as String, UriKind.RelativeOrAbsolute, out iconUri)) { ImageSource img = new BitmapImage(iconUri); if (null != img) { GreyableImage icon = (o as ManagedContent).Icon as GreyableImage; if (null == icon) icon = new GreyableImage(); icon.Source = img; icon.Stretch = Stretch.None; icon.SnapsToDevicePixels = true; return icon; } } } return value; } /// <summary> /// Access to <see cref="DefaultFocusedElementProperty"/> /// </summary> public IInputElement DefaultElement { get { return (IInputElement)GetValue(DefaultFocusedElementProperty); } set { SetValue(DefaultFocusedElementProperty, value); } } /// <summary> /// Gets or sets an element which is focused by default when content is activated /// </summary> public static readonly DependencyProperty DefaultFocusedElementProperty = DependencyProperty.Register("DefaultElement", typeof(IInputElement), typeof(ManagedContent)); FrameworkElement _dragEnabledArea; protected FrameworkElement DragEnabledArea { get { return _dragEnabledArea; } } public override void OnApplyTemplate() { base.OnApplyTemplate(); _dragEnabledArea = GetTemplateChild("PART_DragArea") as FrameworkElement; if (_dragEnabledArea != null) { _dragEnabledArea.MouseDown += new MouseButtonEventHandler(OnDragMouseDown); _dragEnabledArea.MouseMove += new MouseEventHandler(OnDragMouseMove); _dragEnabledArea.MouseUp += new MouseButtonEventHandler(OnDragMouseUp); _dragEnabledArea.MouseLeave += new MouseEventHandler(OnDragMouseLeave); } } #region Mouse management protected virtual void OnDragStart(Point ptMouse, Point ptrelativeMouse) { } Point ptStartDrag; bool isMouseDown = false; protected Point StartDragPoint { get { return ptStartDrag; } } protected bool IsMouseDown { get { return isMouseDown; } } protected void ResetIsMouseDownFlag() { isMouseDown = false; } protected virtual void OnDragMouseDown(object sender, MouseButtonEventArgs e) { if (!e.Handled && Manager != null)// && State != DockableContentState.AutoHide) { isMouseDown = true; ptStartDrag = e.GetPosition((IInputElement)System.Windows.Media.VisualTreeHelper.GetParent(this)); } } protected virtual void OnDragMouseMove(object sender, MouseEventArgs e) { } protected virtual void OnDragMouseUp(object sender, MouseButtonEventArgs e) { isMouseDown = false; } Point ptRelativePosition; protected virtual void OnDragMouseLeave(object sender, MouseEventArgs e) { if (!e.Handled && IsMouseDown && Manager != null) { if (!IsMouseCaptured) { Point ptMouseMove = e.GetPosition(this); ManagedContent contentToSwap = null; if (ContainerPane != null) { foreach (ManagedContent content in ContainerPane.Items) { if (content == this) continue; HitTestResult res = VisualTreeHelper.HitTest(content, e.GetPosition(content)); if (res != null) { contentToSwap = content; break; } } } if (contentToSwap != null) { Pane containerPane = ContainerPane; int myIndex = containerPane.Items.IndexOf(this); ContainerPane.Items.RemoveAt(myIndex); int otherIndex = containerPane.Items.IndexOf(contentToSwap); containerPane.Items.RemoveAt(otherIndex); containerPane.Items.Insert(otherIndex, this); containerPane.Items.Insert(myIndex, contentToSwap); containerPane.SelectedItem = this; e.Handled = false; return; } else if (Math.Abs(ptMouseMove.X - StartDragPoint.X) > SystemParameters.MinimumHorizontalDragDistance || Math.Abs(ptMouseMove.Y - StartDragPoint.Y) > SystemParameters.MinimumVerticalDragDistance) { ptRelativePosition = e.GetPosition(DragEnabledArea); ResetIsMouseDownFlag(); OnDragStart(StartDragPoint, ptRelativePosition); e.Handled = true; } } } isMouseDown = false; } #endregion protected override void OnMouseDown(MouseButtonEventArgs e) { base.OnMouseDown(e); if (!e.Handled) { SetAsActive(); IInputElement focusedElement = e.Source as IInputElement; if (focusedElement != null) Keyboard.Focus(focusedElement); } } protected override void OnKeyDown(KeyEventArgs e) { if (e.Key == Key.Enter) { if (ContainerPane != null) ContainerPane.SelectedItem = this; } base.OnKeyDown(e); } public Pane ContainerPane { get { Pane containerPane = Parent as Pane; if (containerPane != null) return containerPane; return this.FindVisualAncestor<Pane>(false); } } internal DockingManager Manager { get { if (ContainerPane != null) return ContainerPane.GetManager(); return null; } } protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e) { base.OnGotKeyboardFocus(e); Debug.WriteLine(string.Format("[{0}].OnGotKeyboardFocus() Source={1} NewFocus={2} OldFocus={3}", this.Name, e.Source.GetType().ToString(), e.NewFocus.GetType().ToString(), e.OldFocus == null ? "<null>" : e.OldFocus.GetType().ToString())); if (Manager != null && this.IsKeyboardFocusWithin)// && Manager.ActiveContent != this) { Manager.ActiveContent = this; } } protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e) { Debug.WriteLine(string.Format("[{0}].OnLostKeyboardFocus() Source={1} NewFocus={2} OldFocus={3}", this.Name, e.Source.GetType().ToString(), e.NewFocus == null ? "<null>" : e.NewFocus.GetType().ToString(), e.OldFocus == null ? "<null>" : e.OldFocus.GetType().ToString())); base.OnLostKeyboardFocus(e); } bool _isActiveContent = false; /// <summary> /// Returns true if the content is the currently active content. /// </summary> /// <remarks>Use <see cref="SetAsActive"/> method to set a content as active.</remarks> public bool IsActiveContent { get { return _isActiveContent; } internal set { if (_isActiveContent != value) { _isActiveContent = value; NotifyPropertyChanged("IsActiveContent"); if (IsActiveContentChanged != null) IsActiveContentChanged(this, EventArgs.Empty); if (_isActiveContent && !IsKeyboardFocused) { Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(delegate { if (_isActiveContent && !IsKeyboardFocused) { if (this.Content is WindowsFormsHost) { //Use reflection in order to remove WinForms assembly reference WindowsFormsHost contentHost = this.Content as WindowsFormsHost; object childCtrl = contentHost.GetType().GetProperty("Child").GetValue(contentHost, null); if (childCtrl != null) { Type winFormType = childCtrl.GetType(); bool focused = (bool)winFormType.GetProperty("Focused").GetValue(childCtrl, null); if (!focused) { winFormType.GetMethod("Focus").Invoke(childCtrl, null); } } } else if (DefaultElement != null) { Debug.WriteLine("Try to set kb focus to " + DefaultElement); IInputElement kbFocused = Keyboard.Focus(DefaultElement); if (kbFocused != null) Debug.WriteLine("Focused element " + kbFocused); else Debug.WriteLine("No focused element"); } else if (this.Content is IInputElement) { //Debug.WriteLine("Try to set kb focus to " + this.Content.ToString()); //IInputElement kbFocused = Keyboard.Focus(this.Content as IInputElement); //if (kbFocused != null) // Debug.WriteLine("Focused element " + kbFocused); //else // Debug.WriteLine("No focused element"); } } })); } } } } public event EventHandler IsActiveContentChanged; /// <summary> /// Set the content as the active content /// </summary> /// <remarks>After this method returns property <see cref="IsActiveContent"/> returns true.</remarks> public void SetAsActive() { if (ContainerPane != null && Manager != null)// && Manager.ActiveContent != this) { ContainerPane.SelectedItem = this; ContainerPane.Focus(); if (Manager != null) Manager.ActiveContent = this; } } bool _isActiveDocument = false; /// <summary> /// Returns true if the document is the currently active document. /// </summary> /// <remarks>Use <see cref="SetAsActive"/> method to set a content as active.</remarks> public bool IsActiveDocument { get { return _isActiveDocument; } internal set { if (_isActiveDocument != value) { if (value) { if (ContainerPane != null) ContainerPane.SelectedItem = this; } _isActiveDocument = value; NotifyPropertyChanged("IsActiveDocument"); } } } bool _isLocked; /// <summary> /// Gets or sets a value indicating if this content is locked (readonly). /// </summary> public bool IsLocked { get { return _isLocked; } set { _isLocked = value; NotifyPropertyChanged("IsLocked"); } } Size _floatingWindowSize = Size.Empty; /// <summary> /// Gets or sets the size of the floating window which hosts this content /// </summary> public Size FloatingWindowSize { get { return _floatingWindowSize; } set { _floatingWindowSize = value; } } ResizeMode _floatingResizeMode = ResizeMode.CanResize; public ResizeMode FloatingResizeMode { get { return _floatingResizeMode; } set { _floatingResizeMode = value; } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion + public bool IsCloseable + { + get { return (bool)GetValue(IsCloseableProperty); } + set { SetValue(IsCloseableProperty, value); } + } + + // Using a DependencyProperty as the backing store for IsCloseable. This enables animation, styling, binding, etc... + public static readonly DependencyProperty IsCloseableProperty = + DependencyProperty.Register("IsCloseable", typeof(bool), typeof(ManagedContent), new UIPropertyMetadata(true)); + } } diff --git a/AvalonDock/AvalonDock/Pane.cs b/AvalonDock/AvalonDock/Pane.cs index 9f06461..e2fce0e 100644 --- a/AvalonDock/AvalonDock/Pane.cs +++ b/AvalonDock/AvalonDock/Pane.cs @@ -1,289 +1,300 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Diagnostics; using System.Collections.Specialized; using System.ComponentModel; namespace AvalonDock { public abstract class Pane : System.Windows.Controls.Primitives.Selector, IDropSurface, IDockableControl, INotifyPropertyChanged { public Pane() { this.Loaded += new RoutedEventHandler(Pane_Loaded); this.Unloaded += new RoutedEventHandler(Pane_Unloaded); } void Pane_Loaded(object sender, RoutedEventArgs e) { //if (GetManager() == null && Parent != null) // throw new InvalidOperationException("Pane must be put under a DockingManager!"); AddDragPaneReferences(); } void Pane_Unloaded(object sender, RoutedEventArgs e) { RemoveDragPaneReferences(); } #region Contents management public bool HasSingleItem { get { return (bool)GetValue(HasSingleItemProperty); } protected set { SetValue(HasSingleItemPropertyKey, value); } } // Using a DependencyProperty as the backing store for HasSingleItem. This enables animation, styling, binding, etc... private static readonly DependencyPropertyKey HasSingleItemPropertyKey = DependencyProperty.RegisterReadOnly("HasSingleItem", typeof(bool), typeof(Pane), new PropertyMetadata(false)); public static readonly DependencyProperty HasSingleItemProperty = HasSingleItemPropertyKey.DependencyProperty; protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { HasSingleItem = (Items.Count == 1); if (Items.Count > 0) { int currentIndex = SelectedIndex; SelectedIndex = -1; if (currentIndex < 0 || currentIndex >= Items.Count) currentIndex = Items.Count - 1; SelectedIndex = currentIndex; } //else // RemoveDragPaneReferences(); base.OnItemsChanged(e); } //void RefreshContentsSelectedProperty() //{ // //foreach (ManagedContent mc in Items) // //{ // // //mc.IsSelected = (mc == SelectedItem); // // //Selector.SetIsSelected(mc // // if (Selector.GetIsSelected(mc)) // // mc.FocusContent(); // //} //} //protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) //{ // if (e.Property == SelectedItemProperty) // RefreshContentsSelectedProperty(); // // SetValue(ActiveContentProperty, SelectedItem); // //if (e.Property == ActiveContentProperty) // //{ // // //SetValue(SelectedItemProperty, ActiveContent); // //} // base.OnPropertyChanged(e); //} #endregion #region IDockableControl Members public virtual bool IsDocked { get { return true; } } #endregion public virtual DockingManager GetManager() { DependencyObject parent = LogicalTreeHelper.GetParent(this); while (parent != null && (!(parent is DockingManager))) parent = LogicalTreeHelper.GetParent(parent); return parent as DockingManager; } #region IDockableControl Members #endregion #region Membri di IDropSurface #region Drag pane services DockingManager _oldManager = null; //protected override void OnVisualParentChanged(DependencyObject oldParent) //{ // base.OnVisualParentChanged(oldParent); // RemoveDragPaneReferences(); // AddDragPaneReferences(); //} protected void RemoveDragPaneReferences() { if (_oldManager != null) { _oldManager.DragPaneServices.Unregister(this); _oldManager = null; } } protected void AddDragPaneReferences() { { _oldManager = GetManager(); if (_oldManager != null) _oldManager.DragPaneServices.Register(this); } } #endregion public abstract bool IsSurfaceVisible {get;} public virtual Rect SurfaceRectangle { get { if (!IsSurfaceVisible) return new Rect(); if (PresentationSource.FromVisual(this) == null) return new Rect(); return new Rect(HelperFunc.PointToScreenWithoutFlowDirection(this, new Point()), new Size(ActualWidth, ActualHeight)); } } public virtual void OnDragEnter(Point point) { GetManager().OverlayWindow.ShowOverlayPaneDockingOptions(this); } public virtual void OnDragOver(Point point) { } public virtual void OnDragLeave(Point point) { GetManager().OverlayWindow.HideOverlayPaneDockingOptions(this); } public virtual bool OnDrop(Point point) { return false; } #endregion public virtual ManagedContent RemoveContent(int index) { ManagedContent contentToRemove = Items[index] as ManagedContent; Items.RemoveAt(index); return contentToRemove; } protected FrameworkElement _partHeader = null; public override void OnApplyTemplate() { base.OnApplyTemplate(); //gets a reference to the header for the pane _partHeader = GetTemplateChild("PART_Header") as FrameworkElement; } internal virtual ResizingPanel GetContainerPanel() { return LogicalTreeHelper.GetParent(this) as ResizingPanel; } /// <summary> /// Closes or hides provided content depending on HideOnClose property /// </summary> internal virtual void CloseOrHide(DockableContent cntToCloseOrHide) + { + CloseOrHide(cntToCloseOrHide, false); + } + + /// <summary> + /// Closes or hides provided content depending on HideOnClose property + /// </summary> + internal virtual void CloseOrHide(DockableContent cntToCloseOrHide, bool force) { Debug.Assert(cntToCloseOrHide != null); + if (!force && !cntToCloseOrHide.IsCloseable) + return; + DockingManager manager = GetManager(); if (cntToCloseOrHide.HideOnClose && manager != null) manager.Hide(cntToCloseOrHide); else RemoveContent(Items.IndexOf(cntToCloseOrHide)); } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion } } diff --git a/AvalonDock/AvalonDock/Properties/AssemblyInfo.cs b/AvalonDock/AvalonDock/Properties/AssemblyInfo.cs index 83b153e..0efa24f 100644 --- a/AvalonDock/AvalonDock/Properties/AssemblyInfo.cs +++ b/AvalonDock/AvalonDock/Properties/AssemblyInfo.cs @@ -1,62 +1,62 @@ #region Using directives using System.Reflection; using System.Runtime.CompilerServices; using System.Resources; using System.Globalization; using System.Windows; using System.Runtime.InteropServices; #endregion // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AvalonDock")] [assembly: AssemblyDescription("WPF docking library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AvalonDock")] [assembly: AssemblyCopyright("Copyright @ Adolfo Marinucci 2007-2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] // Specifies the location in which theme dictionaries are stored for types in an assembly. [assembly: ThemeInfo( // Specifies the location of system theme-specific resource dictionaries for this project. // The default setting in this project is "None" since this default project does not // include these user-defined theme files: // Themes\Aero.NormalColor.xaml // Themes\Classic.xaml // Themes\Luna.Homestead.xaml // Themes\Luna.Metallic.xaml // Themes\Luna.NormalColor.xaml // Themes\Royale.NormalColor.xaml ResourceDictionaryLocation.SourceAssembly, // Specifies the location of the system non-theme specific resource dictionary: // Themes\generic.xaml ResourceDictionaryLocation.SourceAssembly)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: -[assembly: AssemblyVersion("1.2.2648")] +[assembly: AssemblyVersion("1.2.2663")] diff --git a/AvalonDock/AvalonDock/Resources/DockablePaneStyles.xaml b/AvalonDock/AvalonDock/Resources/DockablePaneStyles.xaml index e29103b..0f306cc 100644 --- a/AvalonDock/AvalonDock/Resources/DockablePaneStyles.xaml +++ b/AvalonDock/AvalonDock/Resources/DockablePaneStyles.xaml @@ -1,255 +1,255 @@ <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ad="clr-namespace:AvalonDock"> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/AvalonDock;component/Resources/Brushes.xaml"/> <ResourceDictionary Source="/AvalonDock;component/Resources/Common.xaml"/> <ResourceDictionary Source="/AvalonDock;component/Resources/ManagedContentStyle.xaml"/> </ResourceDictionary.MergedDictionaries> <ContextMenu x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type ad:DockingManager}, ResourceId={x:Static ad:ContextMenuElement.DockablePane}}" > <MenuItem Header="Floating" Command="ad:DockableContent.FloatingCommand" /> <!--<MenuItem Header="Dockable" Command="ad:DockableContent.DockableCommand" />--> <MenuItem Header="Tabbed document" Command="ad:DockableContent.ShowAsDocumentCommand" /> <MenuItem Header="Auto Hide" Command="ad:DockablePane.ToggleAutoHideCommand" /> <MenuItem Header="Hide" - Command="ad:DockableContent.HideCommand" /> + Command="ad:DockableContent.HideCommand" Visibility="{Binding Path=IsCloseable, Converter={x:Static ad:Converters.BoolToVisibilityConverter}}" /> </ContextMenu> <!--DockableContentTabItemStyle--> <Style x:Key="DockableContentTabItemStyle" TargetType="{x:Type ad:DockableContent}"> <Setter Property="FocusVisualStyle" Value="{x:Null}"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ad:DockableContent}"> <Grid SnapsToDevicePixels="True"> <Border x:Name="PART_DragArea" BorderBrush="{StaticResource ManagedContentTabControlNormalBorderBrush}" BorderThickness="1,0,1,1" Margin="0,2,0,0" CornerRadius="0,0,3,3" Background="{StaticResource ManagedContentTabItemNormalBackground}" > <Border x:Name="tabItemIntBorder" Margin="0,1,0,2" BorderBrush="{StaticResource ManagedContentTabControlNormalBorderBrush}"> <Grid Margin="4,0,4,0"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <ad:AlignedImage> <ContentPresenter x:Name="Icon" Grid.Column="0" Margin="1" VerticalAlignment="Center" ContentSource="Icon" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> </ad:AlignedImage> <TextBlock x:Name="tabItemTitle" Grid.Column="1" TextTrimming="CharacterEllipsis" TextWrapping="NoWrap" Text="{TemplateBinding Title}" Margin="2,0,0,0" VerticalAlignment="Center" Foreground="{DynamicResource {x:Static SystemColors.ControlDarkBrushKey}}"/> </Grid> </Border> </Border> <Border x:Name="HighlightBorder" Height="3" VerticalAlignment="Bottom" BorderThickness="0,0,0,0" CornerRadius ="0,0,3,3" BorderBrush="#FFE68B2C" Background="{StaticResource ManagedContentTabItemSelectedBorderBackround}" Visibility="Hidden" /> </Grid> <ControlTemplate.Triggers> <Trigger Property="Selector.IsSelected" Value="true"> <Setter Property="BorderThickness" Value="0" TargetName="tabItemIntBorder"/> <Setter Property="BorderThickness" Value="1,0,1,0" TargetName="PART_DragArea"/> <Setter Property="Background" Value="#FFFCFCFE" TargetName="PART_DragArea"/> <Setter Property="CornerRadius" Value="0,0,3,3" TargetName="PART_DragArea"/> <Setter Property="Visibility" Value="Visible" TargetName="HighlightBorder"/> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" TargetName="tabItemTitle"/> <Setter Property="Margin" Value="0,3,0,2" TargetName="tabItemIntBorder"/> <Setter Property="Margin" Value="0,1,0,0" TargetName="PART_DragArea"/> </Trigger> <Trigger Property="IsMouseOver" Value="true"> <Setter Property="Visibility" Value="Visible" TargetName="HighlightBorder"/> </Trigger> <Trigger Property="Icon" Value="{x:Null}"> <Setter TargetName="Icon" Property="Visibility" Value="Collapsed"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <!--DockablePane--> <Style TargetType="{x:Type ad:DockablePane}"> <Setter Property="Background" Value="{DynamicResource {ComponentResourceKey {x:Type ad:DockingManager}, {x:Static ad:AvalonDockBrushes.DefaultBackgroundBrush}}}"/> <Setter Property="FocusVisualStyle" Value="{x:Null}"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ad:DockablePane}"><!--Background="{TemplateBinding Background}"--> <Border Focusable="True" Background="{TemplateBinding Background}"> <Grid FocusManager.FocusedElement="{Binding ElementName=PART_SelectedContent}"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Border x:Name="PART_Header" Grid.Row="0" Focusable="False" Background="{DynamicResource {ComponentResourceKey {x:Type ad:DockingManager}, {x:Static ad:AvalonDockBrushes.DockablePaneTitleBackground}}}" BorderThickness="1,1,1,0" BorderBrush="DarkGray" Height="18"> <DockPanel LastChildFill="True"> - <Button DockPanel.Dock="Right" Width="15" Height="15" Style="{StaticResource PaneHeaderCommandStyle}" Command="ad:DockablePane.CloseCommand"> + <Button DockPanel.Dock="Right" Width="15" Height="15" Style="{StaticResource PaneHeaderCommandStyle}" Command="ad:DockablePane.CloseCommand" Visibility="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SelectedItem.IsCloseable, Converter={x:Static ad:Converters.BoolToVisibilityConverter}}"> <ad:AlignedImage> <Image Source="Images\PinClose.png" Width="13" Height="13" Stretch="None"/> </ad:AlignedImage> </Button> <Button x:Name="btnPinAutoHide" DockPanel.Dock="Right" Width="15" Height="15" Style="{StaticResource PaneHeaderCommandStyle}" Command="ad:DockablePane.ToggleAutoHideCommand"> <ad:AlignedImage> <Image Source="Images\PinAutoHide.png" Width="13" Height="13" Stretch="None"/> </ad:AlignedImage> </Button> <Button x:Name="PART_ShowContextMenuButton" DockPanel.Dock="Right" Width="15" Height="15" Style="{StaticResource PaneHeaderContextMenuCommandStyle}" Command="ad:DockablePane.ShowOptionsCommand"> <ad:AlignedImage> <Image Source="Images\PinMenu.png" Width="13" Height="13" Stretch="None"/> </ad:AlignedImage> </Button> <TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SelectedItem.Title}" x:Name="paneTitle" Grid.Row="0" Margin="2,0,0,0" TextTrimming="CharacterEllipsis" TextWrapping="NoWrap" VerticalAlignment="Center" Foreground="{DynamicResource {ComponentResourceKey {x:Type ad:DockingManager}, {x:Static ad:AvalonDockBrushes.DockablePaneTitleForeground}}}"/> </DockPanel> </Border> <Border Grid.Row="1" BorderThickness="1,0,1,1" BorderBrush="DarkGray" Background="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SelectedItem.Background}"> <ContentPresenter x:Name="PART_SelectedContent" Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SelectedItem.Content}" KeyboardNavigation.TabNavigation="Local" KeyboardNavigation.DirectionalNavigation="Contained" KeyboardNavigation.TabIndex="1" /> </Border> <Border x:Name="PART_Tabs" Grid.Row="2" Margin ="0,2,0,0" Height ="25" BorderThickness="0,1,0,0" BorderBrush="{StaticResource ManagedContentTabControlNormalBorderBrush}" > </Border> <ad:DockableTabPanel Grid.Row="2" Height ="24" KeyboardNavigation.TabIndex="2" IsItemsHost="True" x:Name="paneTabsPanel" Margin="0,0,0,2" TabItemStyle="{StaticResource DockableContentTabItemStyle}"/> </Grid> </Border> <ControlTemplate.Triggers> <!--<Trigger Property="IsKeyboardFocusWithin" Value="True"> <Setter Property="Background" Value="{StaticResource DockablePaneTitleBackground}" TargetName="PART_Header"/> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ActiveCaptionTextBrushKey}}" TargetName="paneTitle"/> </Trigger>--> <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=SelectedItem.IsActiveContent}" Value="True" > <Setter Property="Background" Value="{DynamicResource {ComponentResourceKey {x:Type ad:DockingManager}, {x:Static ad:AvalonDockBrushes.DockablePaneTitleBackgroundSelected}}}" TargetName="PART_Header"/> <Setter Property="Foreground" Value="{DynamicResource {ComponentResourceKey {x:Type ad:DockingManager}, {x:Static ad:AvalonDockBrushes.DockablePaneTitleForegroundSelected}}}" TargetName="paneTitle"/> </DataTrigger> <!--<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsOptionsMenuOpened}" Value="True" > <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ActiveCaptionBrushKey}}" TargetName="PART_Header"/> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ActiveCaptionTextBrushKey}}" TargetName="paneTitle"/> </DataTrigger>--> <Trigger Property ="ShowHeader" Value="False"> <Setter Property="Visibility" Value="Collapsed" TargetName="PART_Header"/> </Trigger> <Trigger Property ="ShowTabs" Value="False"> <Setter Property="Visibility" Value="Collapsed" TargetName="PART_Tabs"/> </Trigger> <Trigger Property ="HasSingleItem" Value="True"> <Setter Property="Visibility" Value="Collapsed" TargetName="PART_Tabs"/> <Setter Property="Visibility" Value="Collapsed" TargetName="paneTabsPanel"/> </Trigger> <!--<EventTrigger RoutedEvent="FrameworkElement.Loaded"> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:0.200" /> </Storyboard> </BeginStoryboard> </EventTrigger>--> <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=SelectedItem.State}" Value="AutoHide"> <!--<DataTrigger.Value> <ad:DockableContentState> AutoHide </ad:DockableContentState> </DataTrigger.Value>--> <Setter Property="LayoutTransform" TargetName="btnPinAutoHide"> <Setter.Value> <RotateTransform Angle="90"/> </Setter.Value> </Setter> </DataTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> \ No newline at end of file
icsharpcode/SharpDevelop-Vendor
dbb9d355b2675024ae27b9909b24c4360dde8a30
Upload AvalonDock 1.2.2648 to vendor branch.
diff --git a/AvalonDock/AvalonDock/DockableContent.cs b/AvalonDock/AvalonDock/DockableContent.cs index fe6ffab..261ed67 100644 --- a/AvalonDock/AvalonDock/DockableContent.cs +++ b/AvalonDock/AvalonDock/DockableContent.cs @@ -1,570 +1,571 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Diagnostics; using System.Xml; namespace AvalonDock { /// <summary> /// Enumerates all the possible states of <see cref="DockableContent"/> /// </summary> public enum DockableContentState { /// <summary> /// Content is docked to a border of a <see cref="ResizingPanel"/> within as <see cref="DockingManager"/> control /// </summary> Docked, /// <summary> /// Content is hosted by a flyout window and is visible only when user move mouse over an anchor thumb located to a <see cref="DockingManager"/> controlo border /// </summary> AutoHide, /// <summary> /// Content is hosted by a floating window and user can redock is on its <see cref="DockingManager"/> container control /// </summary> DockableWindow, /// <summary> /// Content is hosted by a floating window that can't be docked to a its <see cref="DockingManager"/> container control /// </summary> FloatingWindow, /// <summary> /// Content is hosted into a <see cref="DocmumentPane"/> /// </summary> Document, /// <summary> /// Content is hidden /// </summary> Hidden, } /// <summary> /// Defines how a dockable content can be dragged over a docking manager /// </summary> /// <remarks>This style can be composed with the 'or' operator.</remarks> public enum DockableStyle : uint { /// <summary> /// Content is not dockable at all /// </summary> None = 0x0000, /// <summary> /// Dockable as document /// </summary> Document = 0x0001, /// <summary> /// Dockable to the left border of <see cref="DockingManager"/> /// </summary> LeftBorder = 0x0002, /// <summary> /// Dockable to the right border of <see cref="DockingManager"/> /// </summary> RightBorder = 0x0004, /// <summary> /// Dockable to the top border of <see cref="DockingManager"/> /// </summary> TopBorder = 0x0008, /// <summary> /// Dockable to the bottom border of <see cref="DockingManager"/> /// </summary> BottomBorder= 0x0010, /// <summary> /// A <see cref="DockableContent"/> with this style can be hosted in a <see cref="FloatingWindow"/> /// </summary> Floating = 0x0020, /// <summary> /// A <see cref="DockableContent"/> with this style can be the only one content in a <see cref="DockablePane"/> pane (NOT YET SUPPORTED) /// </summary> /// <remarks>This style is not compatible with <see cref="DockableStyle.Document"/> style</remarks> Single = 0x0040, /// <summary> /// A <see cref="DockableContet"/> with this style can be autohidden. /// </summary> AutoHide = 0x0080, /// <summary> /// Dockable only to a border of a <see cref="DockingManager"/> /// </summary> DockableToBorders = LeftBorder | RightBorder | TopBorder | BottomBorder | AutoHide, /// <summary> /// Dockable to a border of a <see cref="DockingManager"/> and into a <see cref="DocumentPane"/> /// </summary> Dockable = DockableToBorders | Document | Floating, /// <summary> /// Dockable to a border of a <see cref="DockingManager"/> and into a <see cref="DocumentPane"/> but not in autohidden mode (WinForms controls) /// </summary> DockableButNotAutoHidden = Dockable & ~AutoHide } /// <summary> /// Represent a state of a dockable content that can be used to restore it after it's hidden /// </summary> internal class DockableContentStateAndPosition { public readonly Pane ContainerPane = null; public readonly int ChildIndex = -1; public readonly double Width; public readonly double Height; public readonly AnchorStyle Anchor = AnchorStyle.None; public DockableContentStateAndPosition( Pane containerPane, int childIndex, double width, double height, AnchorStyle anchor) { ContainerPane = containerPane; ChildIndex = childIndex; Width = Math.Max(width, 100.0); Height = Math.Max(height, 100.0); Anchor = anchor; } public DockableContentStateAndPosition( DockableContent cntToSave) { ContainerPane = cntToSave.ContainerPane; ChildIndex = ContainerPane.Items.IndexOf(cntToSave); Width = Math.Max(ContainerPane.ActualWidth, 100.0); Height = Math.Max(ContainerPane.ActualHeight, 100.0); DockablePane dockablePane = ContainerPane as DockablePane; if (dockablePane != null) { Anchor = dockablePane.Anchor; } } } /// <summary> /// Identifies a content that can be drag over a <see cref="DockingManager"/> control or hosted by a window floating over it (<see cref="FloatingWindow"/>). /// </summary> public class DockableContent : ManagedContent { static DockableContent() { DefaultStyleKeyProperty.OverrideMetadata(typeof(DockableContent), new FrameworkPropertyMetadata(typeof(DockableContent))); } public DockableContent() { } #region Drag content protected override void OnDragMouseMove(object sender, MouseEventArgs e) { base.OnDragMouseMove(sender, e); } protected override void OnDragStart(Point ptMouse, Point ptRelativeMouse) { if (DockableStyle != DockableStyle.None && State != DockableContentState.AutoHide) { Manager.Drag(this, HelperFunc.PointToScreenWithoutFlowDirection(this, ptMouse), ptRelativeMouse); } base.OnDragStart(ptMouse, ptRelativeMouse); } #endregion #region State Properties & Events public delegate void DockableContentStateHandler(object sender, DockableContentState state); public event DockableContentStateHandler StateChanged; public DockableContentState State { get { return (DockableContentState)GetValue(StatePropertyKey.DependencyProperty); } //protected set { SetValue(StatePropertyKey, value); } protected set { SetValue(StatePropertyKey, value); if (StateChanged != null) StateChanged(this, value); } } // Using a DependencyProperty as the backing store for State. This enables animation, styling, binding, etc... public static readonly DependencyPropertyKey StatePropertyKey = DependencyProperty.RegisterReadOnly("State", typeof(DockableContentState), typeof(DockableContent), new UIPropertyMetadata(DockableContentState.Docked)); DockableStyle _dockableStyle = DockableStyle.Dockable; /// <summary> /// Get or sets a value that indicates how a dockable content can be dragged over and docked to a <see cref="DockingManager"/> /// </summary> public DockableStyle DockableStyle { get { return _dockableStyle; } set { _dockableStyle = value; } } #endregion #region StateMachine internal void SetStateToAutoHide() { State = DockableContentState.AutoHide; } internal void SetStateToDock() { State = DockableContentState.Docked; } internal void SetStateToDockableWindow() { if (State == DockableContentState.DockableWindow) return; Debug.Assert( State == DockableContentState.Document || State == DockableContentState.Docked || State == DockableContentState.FloatingWindow); State = DockableContentState.DockableWindow; } internal void SetStateToFloatingWindow() { if (State == DockableContentState.FloatingWindow) return; Debug.Assert( State == DockableContentState.Document || State == DockableContentState.Docked || State == DockableContentState.DockableWindow); State = DockableContentState.FloatingWindow; } internal void SetStateToHidden() { State = DockableContentState.Hidden; } internal void SetStateToDocument() { State = DockableContentState.Document; } #endregion #region HideOnClose public static DependencyProperty HideOnCloseKey = DependencyProperty.Register("HideOnClose", typeof(bool), typeof(DockableContent), new PropertyMetadata(true)); public bool HideOnClose { get { return (bool)GetValue(HideOnCloseKey); } set { SetValue(HideOnCloseKey, value); } } #endregion protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); this.CommandBindings.Add( new CommandBinding(FloatingCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(DockableCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(ShowAsDocumentCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(DockablePane.ToggleAutoHideCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(HideCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); } #region Commands static object syncRoot = new object(); private static RoutedUICommand documentCommand = null; public static RoutedUICommand ShowAsDocumentCommand { get { lock (syncRoot) { if (null == documentCommand) { documentCommand = new RoutedUICommand("Tabbed Document", "Document", typeof(DockableContent)); } } return documentCommand; } } private static RoutedUICommand dockableCommand = null; public static RoutedUICommand DockableCommand { get { lock (syncRoot) { if (null == dockableCommand) { dockableCommand = new RoutedUICommand("Dockable", "Dockable", typeof(DockablePane)); } } return dockableCommand; } } private static RoutedUICommand floatingCommand = null; public static RoutedUICommand FloatingCommand { get { lock (syncRoot) { if (null == floatingCommand) { floatingCommand = new RoutedUICommand("F_loating", "Floating", typeof(DockableContent)); } } return floatingCommand; } } private static RoutedUICommand hideCommand = null; public static RoutedUICommand HideCommand { get { lock (syncRoot) { if (null == hideCommand) { hideCommand = new RoutedUICommand("H_ide", "Hide", typeof(DockableContent)); } } return hideCommand; } } internal virtual void OnExecuteCommand(object sender, ExecutedRoutedEventArgs e) { if (!e.Handled && e.Command == DockablePane.ToggleAutoHideCommand) { if ((DockableStyle & DockableStyle.AutoHide) > 0) { ((ContainerPane as DockablePane)).ToggleAutoHide(); e.Handled = true; } } else if (!e.Handled && e.Command == DockableContent.HideCommand) { - Manager.Hide(this); + //Manager.Hide(this); + e.Handled = true; } else if (!e.Handled && e.Command == DockableContent.FloatingCommand) { Manager.Show(this, DockableContentState.FloatingWindow); e.Handled = true; } else if (!e.Handled && e.Command == DockableContent.DockableCommand) { Manager.Show(this, DockableContentState.DockableWindow); e.Handled = true; } else if (!e.Handled && e.Command == DockableContent.ShowAsDocumentCommand) { Manager.Show(this, DockableContentState.Document); e.Handled = true; } } protected virtual void OnCanExecuteCommand(object sender, CanExecuteRoutedEventArgs e) { if (State == DockableContentState.AutoHide) { if (e.Command == DockablePane.ToggleAutoHideCommand || e.Command == DockablePane.CloseCommand || e.Command == DockableContent.HideCommand) e.CanExecute = true; else e.CanExecute = false; } else e.CanExecute = true; } #endregion #region Operations on content /// <summary> /// Remove this content from its parent container pane /// </summary> /// <returns></returns> internal DockableContent DetachFromContainerPane() { if (ContainerPane != null) { int indexOfContent = ContainerPane.Items.IndexOf(this); return ContainerPane.RemoveContent(indexOfContent) as DockableContent; } return null; } DockableContentStateAndPosition _savedStateAndPosition = null; internal DockableContentStateAndPosition SavedStateAndPosition { get { return _savedStateAndPosition; } } internal void SaveCurrentStateAndPosition() { //if (State == DockableContentState.Docked) //{ _savedStateAndPosition = new DockableContentStateAndPosition( this); //} //else //{ // _savedStateAndPosition = null; //} } /// <summary> /// Reset internal state and position of the content /// </summary> /// <remarks>After a <see cref="DockableContent"/> is hidden AvalonDock save its state and position in order to /// restore it correctly when user wants to reshow it calling <see cref="DockingManager.Show"/> function. Call this method /// if you want to reset these data and provide your state and anchor style calling one of the overloads of the function /// <see cref="DockingManager.Show"/>.</remarks> public void ResetSavedStateAndPosition() { _savedStateAndPosition = null; } #endregion #region Save/Restore Content Layout /// <summary> /// Save content specific layout settings /// </summary> /// <param name="storeWriter">Backend store writer</param> /// <remarks>Custom derived class can overloads this method to handle custom layout persistence.</remarks> public virtual void SaveLayout(XmlWriter storeWriter) { if (!FloatingWindowSize.IsEmpty) { storeWriter.WriteAttributeString( "FloatingWindowSize", new SizeConverter().ConvertToInvariantString(FloatingWindowSize)); } if (SavedStateAndPosition != null) { storeWriter.WriteAttributeString( "ChildIndex", SavedStateAndPosition.ChildIndex.ToString()); storeWriter.WriteAttributeString( "Width", SavedStateAndPosition.Width.ToString()); storeWriter.WriteAttributeString( "Height", SavedStateAndPosition.Height.ToString()); storeWriter.WriteAttributeString( "Anchor", SavedStateAndPosition.Anchor.ToString()); } } /// <summary> /// Restore content specific layout settings /// </summary> /// <param name="storeReader">Saved xml element containg content layout settings</param> /// <remarks>Custom derived class must overload this method to restore custom layout settings previously saved trought <see cref="SaveLayout"/>.</remarks> public virtual void RestoreLayout(XmlElement contentElement) { if (contentElement.HasAttribute("FloatingWindowSize")) FloatingWindowSize = (Size)(new SizeConverter()).ConvertFromInvariantString(contentElement.GetAttribute("FloatingWindowSize")); Size effectiveSize = new Size(0d, 0d); if (contentElement.HasAttribute("EffectiveSize")) { // Store effectiveSize = (Size)(new SizeConverter()).ConvertFromInvariantString(contentElement.GetAttribute("EffectiveSize")); } ResizingPanel.SetEffectiveSize(this, effectiveSize); if (contentElement.HasAttribute("ChildIndex")) { _savedStateAndPosition = new DockableContentStateAndPosition( ContainerPane, int.Parse(contentElement.GetAttribute("ChildIndex")), double.Parse(contentElement.GetAttribute("Width")), double.Parse(contentElement.GetAttribute("Height")), (AnchorStyle) Enum.Parse(typeof(AnchorStyle), contentElement.GetAttribute("Anchor")) ); } } #endregion } } diff --git a/AvalonDock/AvalonDock/DockableFloatingWindow.cs b/AvalonDock/AvalonDock/DockableFloatingWindow.cs index 6205113..e0d0c08 100644 --- a/AvalonDock/AvalonDock/DockableFloatingWindow.cs +++ b/AvalonDock/AvalonDock/DockableFloatingWindow.cs @@ -1,272 +1,274 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.ComponentModel; using System.Windows.Markup; using System.Diagnostics; using System.Windows.Threading; using System.Windows.Media.Animation; using System.Windows.Interop; namespace AvalonDock { public class DockableFloatingWindow : FloatingWindow { static DockableFloatingWindow() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml DefaultStyleKeyProperty.OverrideMetadata(typeof(DockableFloatingWindow), new FrameworkPropertyMetadata(typeof(DockableFloatingWindow))); } public DockableFloatingWindow(DockingManager manager) : base(manager) { } Pane _previousPane = null; int _arrayIndexPreviousPane = -1; public DockableFloatingWindow(DockingManager manager, DockableContent content) : this(manager) { //create a new temporary pane FloatingDockablePane pane = new FloatingDockablePane(this); //setup window size //Width = content.ContainerPane.ActualWidth; //Height = content.ContainerPane.ActualHeight; if (content.FloatingWindowSize.IsEmpty) content.FloatingWindowSize = new Size(content.ContainerPane.ActualWidth, content.ContainerPane.ActualHeight); Width = content.FloatingWindowSize.Width; Height = content.FloatingWindowSize.Height; //save current content position in container pane _previousPane = content.ContainerPane; _arrayIndexPreviousPane = _previousPane.Items.IndexOf(content); //pane.SetValue(ResizingPanel.ResizeWidthProperty, _previousPane.GetValue(ResizingPanel.ResizeWidthProperty)); //pane.SetValue(ResizingPanel.ResizeHeightProperty, _previousPane.GetValue(ResizingPanel.ResizeHeightProperty)); //remove content from container pane content.ContainerPane.RemoveContent(_arrayIndexPreviousPane); //add content to my temporary pane pane.Items.Add(content); //let templates access this pane HostedPane = pane; //Change state on contents IsDockableWindow = true; DocumentPane originalDocumentPane = _previousPane as DocumentPane; if (originalDocumentPane != null) originalDocumentPane.CheckContentsEmpty(); } public DockableFloatingWindow(DockingManager manager, DockablePane dockablePane) : this(manager) { //create a new temporary pane FloatingDockablePane pane = new FloatingDockablePane(this); //setup window size ManagedContent selectedContent = dockablePane.SelectedItem as ManagedContent; if (selectedContent != null && selectedContent.FloatingWindowSize.IsEmpty) selectedContent.FloatingWindowSize = new Size(dockablePane.ActualWidth, dockablePane.ActualHeight); if (selectedContent != null) { Width = selectedContent.FloatingWindowSize.Width; Height = selectedContent.FloatingWindowSize.Height; this.ResizeMode = selectedContent.FloatingResizeMode; } else { Width = dockablePane.ActualWidth; Height = dockablePane.ActualHeight; } //Width = dockablePane.ActualWidth; //Height = dockablePane.ActualHeight; ////save current content position in container pane //pane.SetValue(ResizingPanel.ResizeWidthProperty, dockablePane.GetValue(ResizingPanel.ResizeWidthProperty)); //pane.SetValue(ResizingPanel.ResizeHeightProperty, dockablePane.GetValue(ResizingPanel.ResizeHeightProperty)); int selectedIndex = dockablePane.SelectedIndex; //remove contents from container pane and insert in hosted pane while (dockablePane.Items.Count > 0) { ManagedContent content = dockablePane.RemoveContent(0); //add content to my temporary pane pane.Items.Add(content); } //let templates access this pane HostedPane = pane; HostedPane.SelectedIndex = selectedIndex; //Change state on contents IsDockableWindow = true; } protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); if (HostedPane == null) HostedPane = Content as FloatingDockablePane; if (HostedPane != null) { Content = HostedPane; } } protected override void OnClosed(EventArgs e) { base.OnClosed(e); while (HostedPane.Items.Count > 0) { - Manager.Hide(HostedPane.Items[0] as DockableContent); + //Manager.Hide(HostedPane.Items[0] as DockableContent); + HostedPane.CloseOrHide(HostedPane.Items[0] as DockableContent); } Manager.UnregisterFloatingWindow(this); } public override Pane ClonePane() { DockablePane paneToAnchor = new DockablePane(); //transfer the resizing panel sizes //paneToAnchor.SetValue(ResizingPanel.ResizeWidthProperty, // HostedPane.GetValue(ResizingPanel.ResizeWidthProperty)); //paneToAnchor.SetValue(ResizingPanel.ResizeHeightProperty, // HostedPane.GetValue(ResizingPanel.ResizeHeightProperty)); ResizingPanel.SetEffectiveSize(paneToAnchor, new Size(Width, Height)); int selectedIndex = HostedPane.SelectedIndex; //transfer contents from hosted pane in the floating window and //the new created dockable pane while (HostedPane.Items.Count > 0) { paneToAnchor.Items.Add( HostedPane.RemoveContent(0)); } paneToAnchor.SelectedIndex = selectedIndex; return paneToAnchor; } protected override void OnExecuteCommand(object sender, ExecutedRoutedEventArgs e) { if (e.Command == TabbedDocumentCommand) { DockableContent currentContent = HostedPane.SelectedItem as DockableContent; Manager.MainDocumentPane.Items.Insert(0, HostedPane.RemoveContent(HostedPane.SelectedIndex)); Manager.MainDocumentPane.SelectedIndex = 0; currentContent.SetStateToDocument(); if (HostedPane.Items.Count == 0) this.Close(); e.Handled = true; } else if (e.Command == CloseCommand) { - DockableContent currentContent = HostedPane.SelectedItem as DockableContent; - Manager.Hide(currentContent); + //DockableContent currentContent = HostedPane.SelectedItem as DockableContent; + //Manager.Hide(currentContent); + HostedPane.CloseOrHide(); if (HostedPane.Items.Count == 0) this.Close(); e.Handled = true; } base.OnExecuteCommand(sender, e); } protected override void Redock() { if (_previousPane != null) { if (_previousPane.GetManager() == null) { DockablePane newContainerPane = new DockablePane(); newContainerPane.Items.Add(HostedPane.RemoveContent(0)); newContainerPane.SetValue(ResizingPanel.ResizeWidthProperty, _previousPane.GetValue(ResizingPanel.ResizeWidthProperty)); newContainerPane.SetValue(ResizingPanel.ResizeHeightProperty, _previousPane.GetValue(ResizingPanel.ResizeHeightProperty)); Manager.Anchor(newContainerPane, ((DockablePane)_previousPane).Anchor); } else { if (_arrayIndexPreviousPane > _previousPane.Items.Count) _arrayIndexPreviousPane = _previousPane.Items.Count; DockableContent currentContent = HostedPane.Items[0] as DockableContent; _previousPane.Items.Insert(_arrayIndexPreviousPane, HostedPane.RemoveContent(0)); _previousPane.SelectedIndex = _arrayIndexPreviousPane; currentContent.SetStateToDock(); } this.Close(); } base.Redock(); } } } diff --git a/AvalonDock/AvalonDock/DockablePane.cs b/AvalonDock/AvalonDock/DockablePane.cs index af5c087..a58a746 100644 --- a/AvalonDock/AvalonDock/DockablePane.cs +++ b/AvalonDock/AvalonDock/DockablePane.cs @@ -1,502 +1,499 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Diagnostics; using System.ComponentModel; using System.Collections; namespace AvalonDock { /// <summary> /// Anchor types /// </summary> public enum AnchorStyle { /// <summary> /// No anchor style, while content is hosted in a <see cref="DocumentPane"/> or a <see cref="FloatingWindow"/> /// </summary> None, /// <summary> /// Top border anchor /// </summary> Top, /// <summary> /// Left border anchor /// </summary> Left, /// <summary> /// Bottom border anchor /// </summary> Bottom, /// <summary> /// Right border anchor /// </summary> Right } public class DockablePane : Pane { static DockablePane() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml DefaultStyleKeyProperty.OverrideMetadata(typeof(DockablePane), new FrameworkPropertyMetadata(typeof(DockablePane))); } protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); this.CommandBindings.Add( new CommandBinding(ShowOptionsCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(ToggleAutoHideCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(CloseCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); } public DockablePane() { this.Loaded += new RoutedEventHandler(DockablePane_Loaded); this.Unloaded += new RoutedEventHandler(DockablePane_Unloaded); } void DockablePane_Loaded(object sender, RoutedEventArgs e) { } void DockablePane_Unloaded(object sender, RoutedEventArgs e) { UnloadOptionsContextMenu(); } #region Dependency properties public bool ShowHeader { get { return (bool)GetValue(ShowHeaderProperty); } set { SetValue(ShowHeaderProperty, value); } } // Using a DependencyProperty as the backing store for ActiveContent. This enables animation, styling, binding, etc... public static readonly DependencyProperty ShowHeaderProperty = DependencyProperty.Register("ShowHeader", typeof(bool), typeof(DockablePane), new UIPropertyMetadata(true)); public bool ShowTabs { get { return (bool)GetValue(ShowTabsProperty); } set { SetValue(ShowTabsProperty, value); } } // Using a DependencyProperty as the backing store for ShowTabs. This enables animation, styling, binding, etc... public static readonly DependencyProperty ShowTabsProperty = DependencyProperty.Register("ShowTabs", typeof(bool), typeof(DockablePane), new UIPropertyMetadata(true)); public AnchorStyle Anchor { get { return (AnchorStyle)GetValue(AnchorPropertyKey.DependencyProperty); } internal set { SetValue(AnchorPropertyKey, value); } } // Using a DependencyProperty as the backing store for Anchor. This enables animation, styling, binding, etc... public static readonly DependencyPropertyKey AnchorPropertyKey = DependencyProperty.RegisterAttachedReadOnly("Anchor", typeof(AnchorStyle), typeof(DockablePane), new UIPropertyMetadata(AnchorStyle.None)); public override void OnApplyTemplate() { base.OnApplyTemplate(); if (_partHeader != null) { _partHeader.MouseDown += new MouseButtonEventHandler(OnHeaderMouseDown); _partHeader.MouseMove += new MouseEventHandler(OnHeaderMouseMove); _partHeader.MouseUp += new MouseButtonEventHandler(OnHeaderMouseUp); _partHeader.MouseEnter += new MouseEventHandler(OnHeaderMouseEnter); _partHeader.MouseLeave += new MouseEventHandler(OnHeaderMouseLeave); } _optionsContextMenuPlacementTarget = GetTemplateChild("PART_ShowContextMenuButton") as UIElement; } #endregion public override bool IsSurfaceVisible { get { foreach (ManagedContent managedContent in Items) { if (managedContent is DocumentContent) continue; if (((DockableContent)managedContent).State == DockableContentState.Docked) return true; } return false; } } #region OptionsContextMenu ContextMenu cxOptions = null; UIElement _optionsContextMenuPlacementTarget = null; void LoadOptionsContextMenu() { Debug.Assert(cxOptions == null); cxOptions = FindResource(new ComponentResourceKey(typeof(DockingManager), ContextMenuElement.DockablePane)) as ContextMenu; cxOptions.Opened += new RoutedEventHandler(cxOptions_RefreshOpenState); cxOptions.Closed += new RoutedEventHandler(cxOptions_RefreshOpenState); } void UnloadOptionsContextMenu() { if (cxOptions != null) { cxOptions.Opened -= new RoutedEventHandler(cxOptions_RefreshOpenState); cxOptions.Closed -= new RoutedEventHandler(cxOptions_RefreshOpenState); cxOptions = null; } } protected virtual void OpenOptionsContextMenu() { if (cxOptions == null) { LoadOptionsContextMenu(); } if (cxOptions != null) { foreach (MenuItem menuItem in cxOptions.Items) menuItem.CommandTarget = this.SelectedItem as DockableContent; if (_optionsContextMenuPlacementTarget != null) { cxOptions.Placement = PlacementMode.Bottom; cxOptions.PlacementTarget = _optionsContextMenuPlacementTarget; } else { cxOptions.Placement = PlacementMode.MousePoint; cxOptions.PlacementTarget = this; } cxOptions.IsOpen = true; } } void cxOptions_RefreshOpenState(object sender, RoutedEventArgs e) { NotifyPropertyChanged("IsOptionsMenuOpened"); } public bool IsOptionsMenuOpened { get { return cxOptions != null && cxOptions.IsOpen && ( _optionsContextMenuPlacementTarget != null ? cxOptions.PlacementTarget == _optionsContextMenuPlacementTarget : cxOptions.PlacementTarget == this); } } #endregion #region Mouse management void FocusContent() { ManagedContent selectedContent = SelectedItem as ManagedContent; if (selectedContent != null && selectedContent.Content is UIElement) { //UIElement internalContent = selectedContent.Content as UIElement; //bool res = internalContent.Focus(); selectedContent.SetAsActive(); } } Point ptStartDrag; bool isMouseDown = false; protected virtual void OnHeaderMouseDown(object sender, MouseButtonEventArgs e) { if (!e.Handled) { FocusContent(); if (((DockableContent)SelectedItem).State != DockableContentState.AutoHide) { ptStartDrag = e.MouseDevice.GetPosition(this); isMouseDown = true; } } } protected virtual void OnHeaderMouseMove(object sender, MouseEventArgs e) { Point ptMouseMove = e.GetPosition(this); if (!e.Handled && isMouseDown) { if (_partHeader != null && _partHeader.IsMouseOver) { if (!IsMouseCaptured) { if (Math.Abs(ptMouseMove.X - ptStartDrag.X) > SystemParameters.MinimumHorizontalDragDistance || Math.Abs(ptMouseMove.Y - ptStartDrag.Y) > SystemParameters.MinimumVerticalDragDistance) { isMouseDown = false; ReleaseMouseCapture(); DockingManager manager = GetManager(); manager.Drag(this, this.PointToScreenDPI(e.GetPosition(this)), e.GetPosition(this)); e.Handled = true; } } } } } protected virtual void OnHeaderMouseUp(object sender, MouseButtonEventArgs e) { isMouseDown = false; ReleaseMouseCapture(); } protected virtual void OnHeaderMouseEnter(object sender, MouseEventArgs e) { isMouseDown = false; } protected virtual void OnHeaderMouseLeave(object sender, MouseEventArgs e) { isMouseDown = false; } #endregion #region Commands private static object syncRoot = new object(); private static RoutedUICommand optionsCommand = null; public static RoutedUICommand ShowOptionsCommand { get { lock (syncRoot) { if (null == optionsCommand) { optionsCommand = new RoutedUICommand("S_how options", "Options", typeof(DockablePane)); } } return optionsCommand; } } private static RoutedUICommand autoHideCommand = null; public static RoutedUICommand ToggleAutoHideCommand { get { lock (syncRoot) { if (null == autoHideCommand) { autoHideCommand = new RoutedUICommand("A_utohide", "AutoHide", typeof(DockablePane)); } } return autoHideCommand; } } private static RoutedUICommand closeCommand = null; public static RoutedUICommand CloseCommand { get { lock (syncRoot) { if (null == closeCommand) { closeCommand = new RoutedUICommand("C_lose", "Close", typeof(DockablePane)); } } return closeCommand; } } internal virtual void OnExecuteCommand(object sender, ExecutedRoutedEventArgs e) { if (e.Command == ToggleAutoHideCommand) { ToggleAutoHide(); e.Handled = true; } else if (e.Command == CloseCommand) { - Close(); + CloseOrHide(); e.Handled = true; } else if (e.Command == ShowOptionsCommand) { OpenOptionsContextMenu(); e.Handled = true; } } protected virtual void OnCanExecuteCommand(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } #endregion public override bool IsDocked { get { return IsSurfaceVisible; } } public DockableStyle GetCumulativeDockableStyle() { DockableStyle style = DockableStyle.Dockable; if (Items.Count == 1 && Items[0] is DocumentContent) style = DockableStyle.Document; else { foreach (DockableContent content in this.Items) { style &= content.DockableStyle; } } return style; } public override ManagedContent RemoveContent(int index) { ManagedContent content = base.RemoveContent(index); if (Items.Count == 0) { ResizingPanel containerPanel = Parent as ResizingPanel; if (containerPanel != null) containerPanel.RemoveChild(this); } return content; } protected virtual void CheckItems(IList newItems) { foreach (object newItem in newItems) { if (!(newItem is DockableContent)) throw new InvalidOperationException("DockablePane can contain only DockableContents!"); } } protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (e.NewItems != null) CheckItems(e.NewItems); base.OnItemsChanged(e); } #region Dockable Pane operations /// <summary> /// Show/Hide a flyout window containing this pane /// </summary> internal virtual void ToggleAutoHide() { bool flag = true; foreach (DockableContent cnt in this.Items) { if ((cnt.DockableStyle & DockableStyle.AutoHide) == 0) { flag = false; break; } } if (flag && GetManager() != null) GetManager().ToggleAutoHide(this); } + /// <summary> - /// Close current content + /// Closes or hides current content depending on HideOnClose property /// </summary> - internal virtual void Close() + internal void CloseOrHide() { - //GetManager().Hide(SelectedItem as DockableContent); - if (SelectedItem is DockableContent) - { - DockableContent item = SelectedItem as DockableContent; - if (item.HideOnClose) - GetManager().Hide(SelectedItem as DockableContent); - else - this.Items.Remove(SelectedItem as DockableContent); - } + CloseOrHide(SelectedItem as DockableContent); } + + + + #endregion } } diff --git a/AvalonDock/AvalonDock/DockingManager.cs b/AvalonDock/AvalonDock/DockingManager.cs index 25cc397..30caddd 100644 --- a/AvalonDock/AvalonDock/DockingManager.cs +++ b/AvalonDock/AvalonDock/DockingManager.cs @@ -1,859 +1,863 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Diagnostics; using System.Windows.Interop; using System.ComponentModel; using System.IO; using System.Xml; using System.Linq; using System.Collections; using System.Collections.Specialized; namespace AvalonDock { /// <summary> /// Represents a control which manages a dockable layout for its children /// </summary> public class DockingManager : System.Windows.Controls.ContentControl, IDropSurface, INotifyPropertyChanged, IDisposable { static DockingManager() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml DefaultStyleKeyProperty.OverrideMetadata(typeof(DockingManager), new FrameworkPropertyMetadata(typeof(DockingManager))); } public DockingManager() { DragPaneServices.Register(this); this.Unloaded += new RoutedEventHandler(DockingManager_Unloaded); this.Loaded += new RoutedEventHandler(DockingManager_Loaded); } #region Control lifetime management ~DockingManager() { Dispose(false); } bool _isControlLoaded = false; void DockingManager_Loaded(object sender, RoutedEventArgs e) { foreach (FloatingWindow floatingWindow in _floatingWindows) { floatingWindow.Owner = Window.GetWindow(this); floatingWindow.Show(); } DragPaneServices.Register(this); _isControlLoaded = true; } void DockingManager_Unloaded(object sender, RoutedEventArgs e) { //cleanup pending resources HideAutoHideWindow(); if (_wndInteropWrapper != null) { _wndInteropWrapper.OnWindowPosChanging -= new EventHandler(_wndInteropWrapper_OnWindowPosChanging); _wndInteropWrapper.Dispose(); _wndInteropWrapper = null; } if (_overlayWindow != null) { _overlayWindow.Close(); _overlayWindow = null; } foreach (FloatingWindow floatingWindow in _floatingWindows) floatingWindow.Hide(); //navigator windows are now automatically disposed when //no longer used. In this way we avoid WPF bug: //http://social.msdn.microsoft.com/forums/en/wpf/thread/f3fc5b7e-e035-4821-908c-b6c07e5c7042/ //if (navigatorWindow != null) //{ // navigatorWindow.Close(); // navigatorWindow = null; //} //if (documentNavigatorWindow != null) //{ // documentNavigatorWindow.Close(); // documentNavigatorWindow = null; //} DragPaneServices.Unregister(this); _isControlLoaded = false; } /// <summary> /// Call this function if you want to deallocate external floating windows, that otherwise are closed when main window is closed. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } bool _disposed = false; protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { while (_floatingWindows.Count > 0) { _floatingWindows[0].Owner = null; _floatingWindows[0].Close(); } } _disposed = true; } #endregion Panel _leftAnchorTabPanel; Panel _rightAnchorTabPanel; Panel _topAnchorTabPanel; Panel _bottomAnchorTabPanel; List<Panel> _anchorTabPanels = new List<Panel>(); bool _OnApplyTemplateFlag = false; Panel ReplaceAnchorTabPanel(Panel oldPanel, Panel newPanel) { if (oldPanel == null) { _anchorTabPanels.Add(newPanel); return newPanel; } else { _anchorTabPanels.Remove(oldPanel); while (oldPanel.Children.Count > 0) { UIElement tabToTransfer = oldPanel.Children[0]; oldPanel.Children.RemoveAt(0); newPanel.Children.Add(tabToTransfer); } _anchorTabPanels.Add(newPanel); return newPanel; } } /// <summary> /// Overriden to get a reference to underlying template elements /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); Panel leftPanel = GetTemplateChild("PART_LeftAnchorTabPanel") as Panel; if (leftPanel == null) throw new ArgumentException("PART_LeftAnchorTabPanel template child element not fount!"); Panel rightPanel = GetTemplateChild("PART_RightAnchorTabPanel") as Panel; if (rightPanel == null) throw new ArgumentException("PART_RightAnchorTabPanel template child element not fount!"); Panel topPanel = GetTemplateChild("PART_TopAnchorTabPanel") as Panel; if (topPanel == null) throw new ArgumentException("PART_TopAnchorTabPanel template child element not fount!"); Panel bottomPanel = GetTemplateChild("PART_BottomAnchorTabPanel") as Panel; if (bottomPanel == null) throw new ArgumentException("PART_BottomAnchorTabPanel template child element not fount!"); _leftAnchorTabPanel = ReplaceAnchorTabPanel(_leftAnchorTabPanel, leftPanel); _rightAnchorTabPanel = ReplaceAnchorTabPanel(_rightAnchorTabPanel, rightPanel); _topAnchorTabPanel = ReplaceAnchorTabPanel(_topAnchorTabPanel, topPanel); _bottomAnchorTabPanel = ReplaceAnchorTabPanel(_bottomAnchorTabPanel, bottomPanel); _OnApplyTemplateFlag = true; } #region Access to contents and pane ManagedContent _activeDocument = null; /// <summary> /// Get or set the active document /// </summary> /// <remarks>The active document not neessary receive keyboard focus. To set keyboard focus on a content see <see cref="ActiveContent"/></remarks> public ManagedContent ActiveDocument { get { return _activeDocument; } set { //Debug.WriteLine(string.Format("SetActiveDocument to '{0}'", value != null ? value.Name : "null")); if (_activeDocument != value/* && value.ContainerPane is DocumentPane*/) { if (value != null && (value.FindVisualAncestor<DocumentPane>(false) == null && !(value is DocumentContent)) ) { //value is not contained in a document pane/ documentfloatingwindow so cant be the active document! return; } List<ManagedContent> listOfAllDocuments = FindContents<ManagedContent>(); listOfAllDocuments.ForEach((ManagedContent cnt) => { cnt.IsActiveDocument = cnt == value; }); _activeDocument = value; NotifyPropertyChanged("ActiveDocument"); + + if (ActiveContent == null) + ActiveContent = value; } } } ManagedContent _activeContent = null; /// <summary> /// Get or set the active content /// </summary> /// <remarks>An activated content is automatically selected in its container pane and receive logical as well keyboard focus.</remarks> public ManagedContent ActiveContent { get { return _activeContent; } internal set { //Debug.WriteLine(string.Format("SetActiveContent to '{0}'", value != null ? value.Name : "null")); ActiveDocument = value; if (_activeContent != value) { List<ManagedContent> listOfAllContents = FindContents<ManagedContent>(); listOfAllContents.ForEach((ManagedContent cnt) => { cnt.IsActiveContent = (value == cnt); }); _floatingWindows.ForEach((DockableFloatingWindow fw) => { foreach (DockableContent cnt in fw.HostedPane.Items) { cnt.IsActiveContent = (value == cnt); } }); if (_flyoutWindow != null) { foreach (DockableContent cnt in _flyoutWindow.ReferencedPane.Items) { cnt.IsActiveContent = (value == cnt); } } _activeContent = value; NotifyPropertyChanged("ActiveContent"); } } } /// <summary> /// Gets the active dockable content /// </summary> /// <remarks>If no dockbale content us active at the moment returns null.</remarks> public DockableContent ActiveDockableContent { get { IInputElement focusedElement = FocusManager.GetFocusedElement(this); return focusedElement as DockableContent; } } /// <summary> /// Gets an array of all dockable contents currenty managed /// </summary> public DockableContent[] DockableContents { get { List<DockableContent> contents = FindContents<DockableContent>(); - foreach (FloatingWindow flWindow in _floatingWindows) - { - foreach (DockableContent content in flWindow.HostedPane.Items) - contents.Add(content); - } + //FindContents already returns contents from FloatingWindows (sg #68987) + //foreach (FloatingWindow flWindow in _floatingWindows) + //{ + // foreach (DockableContent content in flWindow.HostedPane.Items) + // contents.Add(content); + //} foreach (DockableContent content in _hiddenContents) contents.Add(content); return contents.ToArray(); } } /// <summary> /// Gets an array of all document contents /// </summary> public DocumentContent[] Documents { get { return FindContents<DocumentContent>().ToArray<DocumentContent>(); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Bindable(true)] public IEnumerable DocumentsSource { get { return (IEnumerable)GetValue(DocumentsSourceProperty); } set { SetValue(DocumentsSourceProperty, value); } } // Using a DependencyProperty as the backing store for DocumentsSource. This enables animation, styling, binding, etc... public static readonly DependencyProperty DocumentsSourceProperty = DependencyProperty.Register("DocumentsSource", typeof(IEnumerable), typeof(DockingManager), new UIPropertyMetadata(null, new PropertyChangedCallback((s, e) => ((DockingManager)s).OnDocumentsSourceChanged(e.OldValue as IEnumerable, e.NewValue as IEnumerable)))); void OnDocumentsSourceChanged(IEnumerable oldSource, IEnumerable newSource) { if (oldSource != null) { INotifyCollectionChanged oldSourceNotityIntf = oldSource as INotifyCollectionChanged; if (oldSourceNotityIntf != null) oldSourceNotityIntf.CollectionChanged -= new NotifyCollectionChangedEventHandler(DocumentsSourceCollectionChanged); } if (newSource != null) { INotifyCollectionChanged newSourceNotityIntf = newSource as INotifyCollectionChanged; if (newSourceNotityIntf != null) newSourceNotityIntf.CollectionChanged += new NotifyCollectionChangedEventHandler(DocumentsSourceCollectionChanged); } } void DocumentsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Reset) { DocumentContent[] docs = this.Documents; foreach (DocumentContent doc in docs) doc.Close(); } if (MainDocumentPane == null) return; if (e.Action == NotifyCollectionChangedAction.Remove || e.Action == NotifyCollectionChangedAction.Replace) { foreach (object newDoc in e.OldItems) { if (newDoc is DocumentContent) (newDoc as DocumentContent).InternalClose(); else if (newDoc is FrameworkElement) { DocumentContent docContainer = ((FrameworkElement)newDoc).Parent as DocumentContent; if (docContainer != null) docContainer.InternalClose(); } } } if (e.Action == NotifyCollectionChangedAction.Add || e.Action == NotifyCollectionChangedAction.Replace) { foreach (object newDoc in e.NewItems) { if (newDoc is DocumentContent) MainDocumentPane.Items.Add(newDoc); else if (newDoc is FrameworkElement) //limit objects to be at least framework elements { DocumentContent docContainer = new DocumentContent(); docContainer.Content = newDoc; MainDocumentPane.Items.Add(docContainer); } } } } /// <summary> /// Returns the main document pane /// </summary> /// <param name="parentPanel"></param> /// <returns></returns> internal static DocumentPane GetMainDocumentPane(ResizingPanel parentPanel) { foreach (UIElement child in parentPanel.Children) { if (child is DocumentPane) return child as DocumentPane; if (child is ResizingPanel) { DocumentPane foundDocPane = GetMainDocumentPane(child as ResizingPanel); if (foundDocPane != null) return foundDocPane; } } return null; } internal static bool IsPanelContainingDocumentPane(ResizingPanel parentPanel) { foreach (UIElement child in parentPanel.Children) { if (child is DocumentPane) return true; if (child is ResizingPanel) { bool foundDocPane = IsPanelContainingDocumentPane(child as ResizingPanel); if (foundDocPane) return foundDocPane; } } return false; } internal void EnsurePanePositionIsValid(DocumentPane pane) { if (pane == MainDocumentPane) return; //A document pane must be at maindocument pane level or deeper if (MainDocumentPane.Parent == this) { throw new InvalidOperationException("A document pane can't be positioned at this level!"); } } bool? FindPaneInPanel(ResizingPanel panel, Pane paneToFind) { foreach (UIElement child in panel.Children) { if (child == paneToFind) return true; else if (child is DockablePane) return null; else if (child is ResizingPanel) { bool? found = FindPaneInPanel(child as ResizingPanel, paneToFind); if (found.HasValue && found.Value) return true; } } return false; } DocumentPane _mainDocumentPane; /// <summary> /// Gets the main <see cref="DocumentPane"/> that can be used to add new document /// </summary> public DocumentPane MainDocumentPane { get { return _mainDocumentPane; } internal set { if (_mainDocumentPane == null) { _mainDocumentPane = value; if (DocumentsSource != null) { foreach (object newDoc in DocumentsSource) { if (newDoc is DocumentContent) MainDocumentPane.Items.Add(newDoc); else if (newDoc is FrameworkElement) //limit objects to be at least framework elements { DocumentContent docContainer = new DocumentContent(); docContainer.Content = newDoc; MainDocumentPane.Items.Add(docContainer); } } } } else { _mainDocumentPane = value; } } } internal List<T> FindContents<T>() where T : ManagedContent { List<T> resList = new List<T>(); if (Content is Pane) { foreach (ManagedContent c in ((Pane)Content).Items) { if (c is T) { resList.Add((T)c); } } } else if (Content is ResizingPanel) { FindContents<T>(resList, Content as ResizingPanel); } foreach (FloatingWindow flWindow in _floatingWindows) { foreach (ManagedContent c in flWindow.HostedPane.Items) { if (c is T) resList.Add(c as T); } } if (_flyoutWindow != null && _flyoutWindow.ReferencedPane != null) { foreach (ManagedContent c in _flyoutWindow.ReferencedPane.Items) { if (c is T) resList.Add(c as T); } } return resList; } void FindContents<T>(List<T> listOfFoundContents, ResizingPanel parentPanel) where T : ManagedContent { foreach (UIElement child in parentPanel.Children) { if (child is Pane) { foreach (ManagedContent c in ((Pane)child).Items) { if (c is T) { listOfFoundContents.Add((T)c); } } } else if (child is ResizingPanel) { FindContents<T>(listOfFoundContents, child as ResizingPanel); } } } #endregion #region Floating windows management List<DockableFloatingWindow> _floatingWindows = new List<DockableFloatingWindow>(); public DockableFloatingWindow[] FloatingWindows { get { if (_floatingWindows == null || _floatingWindows.Count == 0) return new DockableFloatingWindow[0]; return _floatingWindows.ToArray(); } } internal void RegisterFloatingWindow(DockableFloatingWindow floatingWindow) { if (_floatingWindows != null) { floatingWindow.FlowDirection = this.FlowDirection; _floatingWindows.Add(floatingWindow); } } internal void UnregisterFloatingWindow(DockableFloatingWindow floatingWindow) { if (_floatingWindows != null) _floatingWindows.Remove(floatingWindow); } protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); this.CommandBindings.Clear(); this.CommandBindings.Add(new CommandBinding(ShowNavigatorWindowCommand, OnExecuteCommand, OnCanExecuteCommand)); this.CommandBindings.Add(new CommandBinding(ShowDocumentNavigatorWindowCommand, OnExecuteCommand, OnCanExecuteCommand)); } protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) { if (e.Property == FlowDirectionProperty) { _floatingWindows.ForEach((DockableFloatingWindow fl) => { fl.FlowDirection = FlowDirection; }); if (_flyoutWindow != null) { _flyoutWindow.FlowDirection = FlowDirection; } } base.OnPropertyChanged(e); } #endregion #region Commands private static object syncRoot = new object(); private static RoutedUICommand showNavigatorCommand = null; /// <summary> /// Get the command to show navigator window /// </summary> public static RoutedUICommand ShowNavigatorWindowCommand { get { lock (syncRoot) { if (null == showNavigatorCommand) { showNavigatorCommand = new RoutedUICommand("S_how navigator window", "Navigator", typeof(DockingManager)); showNavigatorCommand.InputGestures.Add(new KeyGesture(Key.Tab, ModifierKeys.Control)); } } return showNavigatorCommand; } } NavigatorWindow navigatorWindow = null; void ShowNavigatorWindow() { HideNavigatorWindow(); if (navigatorWindow == null) { navigatorWindow = new NavigatorWindow(this); navigatorWindow.Owner = Window.GetWindow(this); } Point locDockingManager = this.PointToScreenDPI(new Point()); navigatorWindow.Left = locDockingManager.X; navigatorWindow.Top = locDockingManager.Y; navigatorWindow.Width = this.ActualWidth; navigatorWindow.Height = this.ActualHeight; navigatorWindow.Show(); navigatorWindow.Focus(); } void HideNavigatorWindow() { if (navigatorWindow != null) { navigatorWindow.Close(); navigatorWindow = null; } } void OnExecuteCommand(object sender, ExecutedRoutedEventArgs e) { if (e.Command == ShowNavigatorWindowCommand && ((Keyboard.Modifiers & ModifierKeys.Control)>0) ) { ShowNavigatorWindow(); e.Handled = true; } else if (e.Command == ShowDocumentNavigatorWindowCommand && ((Keyboard.Modifiers & ModifierKeys.Shift) > 0)) { ShowDocumentNavigatorWindow(); e.Handled = true; } } void OnCanExecuteCommand(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } private static RoutedUICommand showDocumentNavigatorCommand = null; /// <summary> /// Get the command to show document navigator window /// </summary> public static RoutedUICommand ShowDocumentNavigatorWindowCommand { get { lock (syncRoot) { if (null == showDocumentNavigatorCommand) { showDocumentNavigatorCommand = new RoutedUICommand("S_how document navigator window", "DocumentNavigator", typeof(DockingManager)); showDocumentNavigatorCommand.InputGestures.Add(new KeyGesture(Key.Tab, ModifierKeys.Shift)); } } return showDocumentNavigatorCommand; } } DocumentNavigatorWindow documentNavigatorWindow = null; void ShowDocumentNavigatorWindow() { HideDocumentNavigatorWindow(); //if (documentNavigatorWindow == null) { documentNavigatorWindow = new DocumentNavigatorWindow(this); documentNavigatorWindow.Owner = Window.GetWindow(this); } if (MainDocumentPane == null) return; Point locMainDocumentPane = MainDocumentPane.PointToScreenDPI(new Point()); documentNavigatorWindow.Left = locMainDocumentPane.X; documentNavigatorWindow.Top = locMainDocumentPane.Y; documentNavigatorWindow.Width = MainDocumentPane.ActualWidth; documentNavigatorWindow.Height = MainDocumentPane.ActualHeight; documentNavigatorWindow.Show(); documentNavigatorWindow.Focus(); } void HideDocumentNavigatorWindow() { //if (documentNavigatorWindow != null) //{ // documentNavigatorWindow.Hide(); // //don't close this window to be more responsive // documentNavigatorWindow.Close(); // documentNavigatorWindow = null; //} } #endregion #region DockablePane operations /// <summary> /// Anchor a dockable pane to a border /// </summary> /// <param name="paneToAnchor"></param> /// <param name="anchor"></param> public void Anchor(Pane paneToAnchor, AnchorStyle anchor) { //remove the pane from its original children collection FrameworkElement parentElement = paneToAnchor.Parent as FrameworkElement; if (anchor == AnchorStyle.None) anchor = AnchorStyle.Right; //Change anchor border according to FlowDirection if (FlowDirection == FlowDirection.RightToLeft) { if (anchor == AnchorStyle.Right) anchor = AnchorStyle.Left; else if (anchor == AnchorStyle.Left) anchor = AnchorStyle.Right; } //parentElement should be a DockingManager or a ResizingPanel if (parentElement is ContentControl) { ((ContentControl)parentElement).Content = null; } //and insert in the top level panel if exist ResizingPanel toplevelPanel = Content as ResizingPanel; Orientation requestedOrientation = (anchor == AnchorStyle.Bottom || anchor == AnchorStyle.Top) ? Orientation.Vertical : Orientation.Horizontal; //if toplevel panel contains only one child then just override the orientation //as requested if (toplevelPanel != null && toplevelPanel.Children.Count == 1) diff --git a/AvalonDock/AvalonDock/DocumentContent.cs b/AvalonDock/AvalonDock/DocumentContent.cs index 5599335..0515782 100644 --- a/AvalonDock/AvalonDock/DocumentContent.cs +++ b/AvalonDock/AvalonDock/DocumentContent.cs @@ -1,289 +1,295 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.ComponentModel; using System.Diagnostics; namespace AvalonDock { /// <summary> /// Represent a document which can be host by a <see cref="DocumentPane"/>. /// </summary> /// <remarks>A document is always hosted by a <see cref="DocumentPane"/> usually in the central area of <see cref="DockingManager"/>. /// It has limited dragging features becaus it can be only moved to an other <see cref="DocumentPane"/> and can't float as a separate window. /// You can access all documents within <see cref="DockingManager"/> with property <see cref="DockingManager.Documents"/>.</remarks> public class DocumentContent : ManagedContent { static DocumentContent() { //DefaultStyleKeyProperty.OverrideMetadata(typeof(DocumentContent), new FrameworkPropertyMetadata(typeof(DocumentContent))); //Control.WidthProperty.OverrideMetadata(typeof(DocumentContent), // new FrameworkPropertyMetadata(new PropertyChangedCallback(OnSizePropertyChanged), new CoerceValueCallback(CourceSizeToNaN))); //Control.HeightProperty.OverrideMetadata(typeof(DocumentContent), // new FrameworkPropertyMetadata(new PropertyChangedCallback(OnSizePropertyChanged), new CoerceValueCallback(CourceSizeToNaN))); } public DocumentContent() { base.PropertyChanged += new PropertyChangedEventHandler(DocumentContent_PropertyChanged); } DateTime _lastActivation = DateTime.MinValue; internal DateTime LastActivation { get { return _lastActivation; } } void DocumentContent_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsActiveContent") { if (IsActiveContent) _lastActivation = DateTime.Now; } } static void OnSizePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { } static object CourceSizeToNaN(DependencyObject sender, object value) { //return double.NaN; return value; } string _infoTip; /// <summary> /// Gets or sets the information text attached to the document content. /// </summary> /// <remarks>This text is usually displayed when users switch between documents and helps them to choose the right one.</remarks> public string InfoTip { get { return _infoTip; } set { _infoTip = value; NotifyPropertyChanged("InfoTip"); } } string _contentTypeDescription; /// <summary> /// Gets or sets a text which describes the type of content contained in this document. /// </summary> public string ContentTypeDescription { get { return _contentTypeDescription; } set { _contentTypeDescription = value; NotifyPropertyChanged("ContentTypeDescription"); } } bool _isFloatingAllowed; /// <summary> /// Gets or sets a value indicating if this document can float over main window (VS2010 Feature). /// </summary> public bool IsFloatingAllowed { get { return _isFloatingAllowed; } set { _isFloatingAllowed = value; NotifyPropertyChanged("IsFloatingAllowed"); } } protected override void OnDragStart(Point ptMouse, Point ptRelativeMouse) { //Manager.Drag(this, this.PointToScreenDPI(ptMouse), ptRelativeMouse); Manager.Drag(this, HelperFunc.PointToScreenWithoutFlowDirection(this, ptMouse), ptRelativeMouse); base.OnDragStart(ptMouse, ptRelativeMouse); } protected override void OnDragMouseMove(object sender, MouseEventArgs e) { base.OnDragMouseMove(sender, e); } protected override void OnDragMouseLeave(object sender, MouseEventArgs e) { base.OnDragMouseLeave(sender, e); } public override void OnApplyTemplate() { base.OnApplyTemplate(); if (DragEnabledArea != null) { DragEnabledArea.InputBindings.Add(new InputBinding(ApplicationCommands.Close, new MouseGesture(MouseAction.MiddleClick))); } } /// <summary> /// Event fired when the document is about to be closed /// </summary> public event EventHandler<CancelEventArgs> Closing; /// <summary> /// Event fired when the document has been closed /// </summary> /// <remarks>Note that when a document is closed property like <see cref="ManagedContent.ContainerPane"/> or <see cref="ManagedContent.Manager"/> returns null.</remarks> public event EventHandler Closed; /// <summary> /// Ovveride this method to handle <see cref="DocumentContent.OnClosing"/> event. /// </summary> protected virtual void OnClosing(CancelEventArgs e) { if (Closing != null && !e.Cancel) { Closing(this, e); } } /// <summary> /// Ovveride this method to handle <see cref="DocumentContent.OnClose"/> event. /// </summary> protected virtual void OnClosed() { if (Closed != null) Closed(this, EventArgs.Empty); } /// <summary> /// Close this content without notifications /// </summary> internal void InternalClose() { + + DocumentPane parentPane = ContainerPane as DocumentPane; DockingManager manager = Manager; + if (manager != null) + { + if (manager.ActiveContent == this) + manager.ActiveContent = null; + + if (manager.ActiveDocument == this) + manager.ActiveDocument = null; + } + if (parentPane != null) { parentPane.Items.Remove(this); parentPane.CheckContentsEmpty(); } else { FloatingDockablePane floatingParentPane = ContainerPane as FloatingDockablePane; if (floatingParentPane != null) { floatingParentPane.RemoveContent(0); - floatingParentPane.FloatingWindow.Close(); + if (floatingParentPane.FloatingWindow != null && + !floatingParentPane.FloatingWindow.IsClosing) + floatingParentPane.FloatingWindow.Close(); } } - if (manager != null) - { - if (manager.ActiveDocument == this) - manager.ActiveDocument = null; - if (manager.ActiveContent == this) - manager.ActiveContent = null; - } } /// <summary> /// Close this document removing it from its parent container /// </summary> /// <remarks>Use this function to close a document and remove it from its parent container. Please note /// that if you simply remove it from its parent <see cref="DocumentPane"/> without call this method, events like /// <see cref="OnClosing"/>/<see cref="OnClosed"/> are not called. /// <para> /// Note:<see cref="DockableContent"/> cannot be closed: AvalonDock simply hide a <see cref="DockableContent"/> removing all the reference to it. /// </para> /// </remarks> public bool Close() { //if documents are attached to an external source via DockingManager.DocumentsSource //let application host handle the document closing by itself if (Manager.DocumentsSource != null) { return Manager.FireRequestDocumentCloseEvent(this); } CancelEventArgs e = new CancelEventArgs(false); OnClosing(e); if (e.Cancel) return false; DockingManager oldManager = Manager; if (Manager != null) Manager.FireDocumentClosingEvent(e); if (e.Cancel) return false; InternalClose(); OnClosed(); if (oldManager != null) oldManager.FireDocumentClosedEvent(); - if (Parent != null) - throw new InvalidOperationException("Parent MUST bu null after Doc is closed"); - + //if (Parent != null) + // throw new InvalidOperationException(); + Debug.Assert(Parent == null, "Parent MUST bu null after Doc is closed"); return true; } } } diff --git a/AvalonDock/AvalonDock/DocumentFloatingWindow.cs b/AvalonDock/AvalonDock/DocumentFloatingWindow.cs index 6072d9e..bc2faad 100644 --- a/AvalonDock/AvalonDock/DocumentFloatingWindow.cs +++ b/AvalonDock/AvalonDock/DocumentFloatingWindow.cs @@ -1,358 +1,362 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.ComponentModel; using System.Windows.Markup; using System.Diagnostics; using System.Windows.Threading; using System.Windows.Media.Animation; using System.Windows.Interop; namespace AvalonDock { public class DocumentFloatingWindow : FloatingWindow { static DocumentFloatingWindow() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml DefaultStyleKeyProperty.OverrideMetadata(typeof(DocumentFloatingWindow), new FrameworkPropertyMetadata(typeof(DocumentFloatingWindow))); Window.AllowsTransparencyProperty.OverrideMetadata(typeof(DocumentFloatingWindow), new FrameworkPropertyMetadata(true)); Window.WindowStyleProperty.OverrideMetadata(typeof(DocumentFloatingWindow), new FrameworkPropertyMetadata(WindowStyle.None)); Window.ShowInTaskbarProperty.OverrideMetadata(typeof(DocumentFloatingWindow), new FrameworkPropertyMetadata(false)); } public DocumentFloatingWindow(DockingManager manager) :base(manager) { } Pane _previousPane = null; int _arrayIndexPreviousPane = -1; public DocumentFloatingWindow(DockingManager manager, DocumentContent content) : this(manager) { //create a new temporary pane FloatingDockablePane pane = new FloatingDockablePane(this); //setup window size Width = content.ContainerPane.ActualWidth; Height = content.ContainerPane.ActualHeight; //save current content position in container pane _previousPane = content.ContainerPane; _arrayIndexPreviousPane = _previousPane.Items.IndexOf(content); pane.SetValue(ResizingPanel.ResizeWidthProperty, _previousPane.GetValue(ResizingPanel.ResizeWidthProperty)); pane.SetValue(ResizingPanel.ResizeHeightProperty, _previousPane.GetValue(ResizingPanel.ResizeHeightProperty)); //remove content from container pane content.ContainerPane.RemoveContent(_arrayIndexPreviousPane); //add content to my temporary pane pane.Items.Add(content); //let templates access this pane HostedPane = pane; if (IsDocumentFloatingAllowed) { AllowsTransparency = false; WindowStyle = WindowStyle.ToolWindow; NotifyPropertyChanged("IsDocumentFloatingAllowed"); } } public bool IsDocumentFloatingAllowed { get { if (HostedPane != null && HostedPane.Items.Count > 0) return ((DocumentContent)HostedPane.Items[0]).IsFloatingAllowed; return false; } } internal override void OnEndDrag() { if (HostedPane.Items.Count > 0) { DocumentContent content = HostedPane.Items[0] as DocumentContent; if (!content.IsFloatingAllowed) { HostedPane.Items.RemoveAt(0); _previousPane.Items.Insert(_arrayIndexPreviousPane, content); _previousPane.SelectedItem = content; Close(); } else { DocumentPane originalDocumentPane = _previousPane as DocumentPane; originalDocumentPane.CheckContentsEmpty(); } } else { DocumentPane originalDocumentPane = _previousPane as DocumentPane; originalDocumentPane.CheckContentsEmpty(); Close(); } base.OnEndDrag(); } public override Pane ClonePane() { DocumentPane paneToAnchor = new DocumentPane(); ////transfer the resizing panel sizes //paneToAnchor.SetValue(ResizingPanel.ResizeWidthProperty, // HostedPane.GetValue(ResizingPanel.ResizeWidthProperty)); //paneToAnchor.SetValue(ResizingPanel.ResizeHeightProperty, // HostedPane.GetValue(ResizingPanel.ResizeHeightProperty)); ResizingPanel.SetEffectiveSize(paneToAnchor, new Size(Width, Height)); //transfer contents from hosted pane in the floating window and //the new created dockable pane while (HostedPane.Items.Count > 0) { paneToAnchor.Items.Add( HostedPane.RemoveContent(0)); } return paneToAnchor; } protected override void OnInitialized(EventArgs e) { if (IsDocumentFloatingAllowed) { if (HostedPane != null) { Content = HostedPane; } } base.OnInitialized(e); } internal override void OnShowSelectionBox() { this.Visibility = Visibility.Hidden; base.OnShowSelectionBox(); } internal override void OnHideSelectionBox() { this.Visibility = Visibility.Visible; base.OnHideSelectionBox(); } #region Commands protected override void OnExecuteCommand(object sender, ExecutedRoutedEventArgs e) { if (e.Command == TabbedDocumentCommand) { DocumentContent currentContent = HostedPane.SelectedItem as DocumentContent; _previousPane.Items.Insert(0, HostedPane.RemoveContent(HostedPane.SelectedIndex)); _previousPane.SelectedIndex = 0; if (HostedPane.Items.Count == 0) this.Close(); e.Handled = true; } else if (e.Command == CloseCommand) { DocumentContent docContent = this.HostedPane.Items[0] as DocumentContent; if (docContent.Close()) { HostedPane.RemoveContent(0); Close(); } e.Handled = true; } base.OnExecuteCommand(sender, e); } #endregion //#region Drag //protected override IntPtr FilterMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) //{ // handled = false; // if (!IsDocumentFloatingAllowed) // return IntPtr.Zero; // switch (msg) // { // case WM_SIZE: // case WM_MOVE: // //HostedPane.ReferencedPane.SaveFloatingWindowSizeAndPosition(this); // break; // case WM_NCLBUTTONDOWN: // if (IsDockableWindow && wParam.ToInt32() == HTCAPTION) // { // short x = (short)((lParam.ToInt32() & 0xFFFF)); // short y = (short)((lParam.ToInt32() >> 16)); // Point clickPoint = this.TransformToDeviceDPI(new Point(x, y)); // Manager.Drag(this, clickPoint, new Point(clickPoint.X - Left, clickPoint.Y - Top)); // handled = true; // } // break; // case WM_NCLBUTTONDBLCLK: // if (IsDockableWindow && wParam.ToInt32() == HTCAPTION) // { // if (IsDockableWindow) // { // if (_previousPane != null) // { // if (_previousPane.GetManager() == null) // { // DockablePane newContainerPane = new DockablePane(); // newContainerPane.Items.Add(HostedPane.RemoveContent(0)); // newContainerPane.SetValue(ResizingPanel.ResizeWidthProperty, _previousPane.GetValue(ResizingPanel.ResizeWidthProperty)); // newContainerPane.SetValue(ResizingPanel.ResizeHeightProperty, _previousPane.GetValue(ResizingPanel.ResizeHeightProperty)); // Manager.Anchor(newContainerPane, ((DockablePane)_previousPane).Anchor); // } // else // { // if (_arrayIndexPreviousPane > _previousPane.Items.Count) // _arrayIndexPreviousPane = _previousPane.Items.Count; // DockableContent currentContent = HostedPane.Items[0] as DockableContent; // _previousPane.Items.Insert(_arrayIndexPreviousPane, HostedPane.RemoveContent(0)); // _previousPane.SelectedIndex = _arrayIndexPreviousPane; // currentContent.SetStateToDock(); // } // this.Close(); // } // handled = true; // } // } // break; // case WM_NCRBUTTONDOWN: // if (wParam.ToInt32() == HTCAPTION) // { // short x = (short)((lParam.ToInt32() & 0xFFFF)); // short y = (short)((lParam.ToInt32() >> 16)); // ContextMenu cxMenu = FindResource(new ComponentResourceKey(typeof(DockingManager), ContextMenuElement.FloatingWindow)) as ContextMenu; // if (cxMenu != null) // { // foreach (MenuItem menuItem in cxMenu.Items) // menuItem.CommandTarget = this; // cxMenu.Placement = PlacementMode.AbsolutePoint; // cxMenu.PlacementRectangle = new Rect(new Point(x, y), new Size(0, 0)); // cxMenu.PlacementTarget = this; // cxMenu.IsOpen = true; // } // handled = true; // } // break; // case WM_NCRBUTTONUP: // if (wParam.ToInt32() == HTCAPTION) // { // handled = true; // } // break; // } // return IntPtr.Zero; //} //#endregion protected override void Redock() { if (_previousPane != null) { if (_previousPane.GetManager() == null) { Manager.MainDocumentPane.Items.Insert(0, HostedPane.RemoveContent(0)); } else { if (_arrayIndexPreviousPane > _previousPane.Items.Count) _arrayIndexPreviousPane = _previousPane.Items.Count; _previousPane.Items.Insert(_arrayIndexPreviousPane, HostedPane.RemoveContent(0)); _previousPane.SelectedIndex = _arrayIndexPreviousPane; } this.Close(); } base.Redock(); } protected override void OnClosing(CancelEventArgs e) { + base.OnClosing(e); + + if (e.Cancel) + return; + if (this.HostedPane.Items.Count > 0) { DocumentContent docContent = this.HostedPane.Items[0] as DocumentContent; if (!docContent.Close()) e.Cancel = true; else this.HostedPane.Items.Remove(docContent); } - base.OnClosing(e); } } } diff --git a/AvalonDock/AvalonDock/DocumentPane.cs b/AvalonDock/AvalonDock/DocumentPane.cs index c2d5e08..68c4a11 100644 --- a/AvalonDock/AvalonDock/DocumentPane.cs +++ b/AvalonDock/AvalonDock/DocumentPane.cs @@ -1,517 +1,517 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Diagnostics; namespace AvalonDock { public class DocumentPane : Pane { static DocumentPane() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml DefaultStyleKeyProperty.OverrideMetadata(typeof(DocumentPane), new FrameworkPropertyMetadata(typeof(DocumentPane))); } public DocumentPane() { this.Loaded += new RoutedEventHandler(DocumentPane_Loaded); } void DocumentPane_Loaded(object sender, RoutedEventArgs e) { if (GetManager() == null) throw new InvalidOperationException("DocumentPane must be put under a DockingManager!"); //try to set this as main document pane if (GetManager().MainDocumentPane == null) { GetManager().MainDocumentPane = this; NotifyPropertyChanged("IsMainDocumentPane"); } else { //or ensure that this document pane is under or at the same level of the MainDocumentPane GetManager().EnsurePanePositionIsValid(this); } } public bool? IsMainDocumentPane { get { if (GetManager() == null) return null; return GetManager().MainDocumentPane == this; } } protected override void OnInitialized(EventArgs e) { this.CommandBindings.Add( new CommandBinding(ShowDocumentsListMenuCommand, ExecutedShowDocumentsListMenuCommand, CanExecuteShowDocumentsListMenuCommand)); this.CommandBindings.Add( new CommandBinding(ApplicationCommands.Close, ExecutedCloseCommand, CanExecuteCloseCommand)); this.CommandBindings.Add( new CommandBinding(CloseCommand, ExecutedCloseCommand, CanExecuteCloseCommand)); this.CommandBindings.Add( new CommandBinding(CloseAllButThisCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(NewHorizontalTabGroupCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(NewVerticalTabGroupCommand, this.OnExecuteCommand, this.OnCanExecuteCommand)); base.OnInitialized(e); } #region DocumentPane Commands #region Show Document Window List Command public static RoutedCommand ShowDocumentsListMenuCommand = new RoutedCommand(); public void ExecutedShowDocumentsListMenuCommand(object sender, ExecutedRoutedEventArgs e) { //MessageBox.Show("ShowOptionsMenu"); ShowDocumentsListMenu(this, null); } public void CanExecuteShowDocumentsListMenuCommand(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } #endregion #region Close Command //ApplicationCommands.Close command.... public void ExecutedCloseCommand(object sender, ExecutedRoutedEventArgs e) { if (GetManager() == null) return; ManagedContent contentToClose = SelectedItem as ManagedContent; if (e.Parameter is ManagedContent) contentToClose = e.Parameter as ManagedContent; DockableContent dockableContent = contentToClose as DockableContent; if (dockableContent != null) - GetManager().Hide(dockableContent); + CloseOrHide(dockableContent); else { DocumentContent documentContent = contentToClose as DocumentContent; documentContent.Close(); //if (documentContent != null) // Items.Remove(documentContent); //CheckContentsEmpty(); } } public void CanExecuteCloseCommand(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } #endregion #region Activate Document Command public static RoutedCommand ActivateDocumentCommand = new RoutedCommand(); public void ExecutedActivateDocumentCommand(object sender, ExecutedRoutedEventArgs e) { ManagedContent doc = e.Parameter as ManagedContent; if (doc != null) { if (!DocumentTabPanel.GetIsHeaderVisible(doc)) { DocumentPane parentPane = doc.ContainerPane as DocumentPane; parentPane.Items.Remove(doc); parentPane.Items.Insert(0, doc); } ////doc.IsSelected = true; ////Selector.SetIsSelected(doc, true); //if (this.GetManager() != null) // this.GetManager().ActiveContent = doc; doc.SetAsActive(); } } public void CanExecuteActivateDocumentCommand(object sender, CanExecuteRoutedEventArgs e) { //ManagedContent doc = e.Parameter as ManagedContent; //if (doc != null && !doc.IsSelected) e.CanExecute = true; } #endregion #region Commands private static object syncRoot = new object(); private static RoutedUICommand closeAllButThisCommand = null; public static RoutedUICommand CloseAllButThisCommand { get { lock (syncRoot) { if (null == closeAllButThisCommand) { closeAllButThisCommand = new RoutedUICommand("Close All But This", "CloseAllButThis", typeof(DocumentPane)); } } return closeAllButThisCommand; } } private static RoutedUICommand closeCommand = null; public static RoutedUICommand CloseCommand { get { lock (syncRoot) { if (null == closeCommand) { closeCommand = new RoutedUICommand("C_lose", "Close", typeof(DocumentPane)); } } return closeCommand; } } private static RoutedUICommand newHTabGroupCommand = null; public static RoutedUICommand NewHorizontalTabGroupCommand { get { lock (syncRoot) { if (null == newHTabGroupCommand) { newHTabGroupCommand = new RoutedUICommand("New Horizontal Tab Group", "NewHorizontalTabGroup", typeof(DocumentPane)); } } return newHTabGroupCommand; } } private static RoutedUICommand newVTabGroupCommand = null; public static RoutedUICommand NewVerticalTabGroupCommand { get { lock (syncRoot) { if (null == newVTabGroupCommand) { newVTabGroupCommand = new RoutedUICommand("New Vertical Tab Group", "NewVerticalTabGroup", typeof(DocumentPane)); } } return newVTabGroupCommand; } } internal virtual void OnExecuteCommand(object sender, ExecutedRoutedEventArgs e) { if (e.Command == CloseAllButThisCommand) { CloseAllButThis(); e.Handled = true; } else if (e.Command == NewHorizontalTabGroupCommand) { NewHorizontalTabGroup(); e.Handled = true; } else if (e.Command == NewVerticalTabGroupCommand) { NewVerticalTabGroup(); e.Handled = true; } } protected virtual void OnCanExecuteCommand(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = this.GetManager() != null; if (e.CanExecute) { if (e.Command == NewHorizontalTabGroupCommand || e.Command == NewVerticalTabGroupCommand) { if (this.Items.Count <= 1) e.CanExecute = false; } } } void CloseAllButThis() { DocumentContent activeContent = GetManager().ActiveDocument as DocumentContent; foreach (DocumentContent cnt in this.GetManager().Documents) { if (cnt != activeContent) cnt.Close(); } } void NewHorizontalTabGroup() { ManagedContent activeContent = SelectedItem as ManagedContent; DocumentPane newContainerPane = new DocumentPane(); int indexOfDocumentInItsContainer = activeContent.ContainerPane.Items.IndexOf(activeContent); activeContent.ContainerPane.RemoveContent(indexOfDocumentInItsContainer); newContainerPane.Items.Add(activeContent); GetManager().Anchor(newContainerPane, this, AnchorStyle.Bottom); } void NewVerticalTabGroup() { ManagedContent activeContent = SelectedItem as ManagedContent; DocumentPane newContainerPane = new DocumentPane(); int indexOfDocumentInItsContainer = activeContent.ContainerPane.Items.IndexOf(activeContent); activeContent.ContainerPane.RemoveContent(indexOfDocumentInItsContainer); newContainerPane.Items.Add(activeContent); GetManager().Anchor(newContainerPane, this, AnchorStyle.Right); } #endregion #endregion UIElement _optionsContextMenuPlacementTarget; public override void OnApplyTemplate() { _optionsContextMenuPlacementTarget = GetTemplateChild("PART_ShowContextMenuButton") as UIElement; base.OnApplyTemplate(); } void ShowDocumentsListMenu(object sender, RoutedEventArgs e) { if (Items.Count == 0) return; //nothings to show ContextMenu cxMenuDocuments = (ContextMenu)FindResource("DocumentsListMenu"); if (cxMenuDocuments != null) { cxMenuDocuments.ItemsSource = Items; cxMenuDocuments.CommandBindings.Add(new CommandBinding(ActivateDocumentCommand, new ExecutedRoutedEventHandler(this.ExecutedActivateDocumentCommand), new CanExecuteRoutedEventHandler(CanExecuteActivateDocumentCommand))); if (_optionsContextMenuPlacementTarget != null) { cxMenuDocuments.Placement = PlacementMode.Bottom; cxMenuDocuments.PlacementTarget = _optionsContextMenuPlacementTarget; } else { cxMenuDocuments.Placement = PlacementMode.MousePoint; cxMenuDocuments.PlacementTarget = this; } cxMenuDocuments.IsOpen = true; } } public override bool IsSurfaceVisible { get { if (IsMainDocumentPane.HasValue && !IsMainDocumentPane.Value && Items.Count == 0) return false; return true; } } protected override void OnMouseDown(MouseButtonEventArgs e) { base.OnMouseDown(e); if (!e.Handled) { if (_partHeader != null && !_partHeader.IsMouseOver) { //prevent document content to start dragging when it is clicked outside of the header area e.Handled = true; } } } internal void CheckContentsEmpty() { if (Items.Count == 0) { bool isMainDocPaneToBeClose = IsMainDocumentPane.HasValue && IsMainDocumentPane.Value; if (isMainDocPaneToBeClose) { DockingManager manager = GetManager(); DocumentPane candidateNewMainDocPane = manager.FindAnotherLogicalChildContained<DocumentPane>(this); if (candidateNewMainDocPane != null) { ResizingPanel containerPanel = Parent as ResizingPanel; if (containerPanel != null) containerPanel.RemoveChild(this); manager.MainDocumentPane = candidateNewMainDocPane; candidateNewMainDocPane.NotifyPropertyChanged("IsMainDocumentPane"); } } else { ResizingPanel containerPanel = Parent as ResizingPanel; if (containerPanel != null) containerPanel.RemoveChild(this); } } } internal override ResizingPanel GetContainerPanel() { return GetParentDocumentPaneResizingPanel(); } internal DocumentPaneResizingPanel GetParentDocumentPaneResizingPanel() { ResizingPanel parentPanel = LogicalTreeHelper.GetParent(this) as ResizingPanel; if (parentPanel == null) return null; while (!(parentPanel is DocumentPaneResizingPanel)) { parentPanel = LogicalTreeHelper.GetParent(parentPanel) as ResizingPanel; if (parentPanel == null) return null; } return parentPanel as DocumentPaneResizingPanel; } public override Rect SurfaceRectangle { get { //it is dragging a document let drop in this document pane if (GetManager().DragPaneServices.FloatingWindow is DocumentFloatingWindow) return base.SurfaceRectangle; //otherwise we should provide a drop surface for all the DocumentPaneResizingPanel DocumentPaneResizingPanel parentPanel = GetParentDocumentPaneResizingPanel(); if (parentPanel == null) return base.SurfaceRectangle; return new Rect(HelperFunc.PointToScreenWithoutFlowDirection(parentPanel, new Point(0, 0)), new Size(parentPanel.ActualWidth, parentPanel.ActualHeight)); //return new Rect(parentPanel.PointToScreen(new Point(0, 0)), new Size(parentPanel.ActualWidth, parentPanel.ActualHeight)); } } protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (e.NewItems != null) { foreach (object newItem in e.NewItems) { if (!(newItem is DockableContent) && !(newItem is DocumentContent)) throw new InvalidOperationException("DocumentPane can contain only DockableContents or DocumentContents!"); if (newItem is DockableContent && (((DockableContent)newItem).DockableStyle & DockableStyle.Document) == 0) { ((DockableContent)newItem).DockableStyle |= DockableStyle.Document; } } } base.OnItemsChanged(e); } protected override void OnSelectionChanged(SelectionChangedEventArgs e) { ManagedContent selectedContent = this.SelectedItem as ManagedContent; if (selectedContent != null && GetManager() != null) GetManager().ActiveDocument = selectedContent; base.OnSelectionChanged(e); } } } diff --git a/AvalonDock/AvalonDock/FloatingWindow.cs b/AvalonDock/AvalonDock/FloatingWindow.cs index f4193e6..8071ffb 100644 --- a/AvalonDock/AvalonDock/FloatingWindow.cs +++ b/AvalonDock/AvalonDock/FloatingWindow.cs @@ -1,403 +1,418 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.ComponentModel; using System.Windows.Markup; using System.Diagnostics; using System.Windows.Threading; using System.Windows.Media.Animation; using System.Windows.Interop; namespace AvalonDock { public abstract class FloatingWindow : Window, INotifyPropertyChanged { static FloatingWindow() { Window.ShowInTaskbarProperty.OverrideMetadata(typeof(FloatingWindow), new FrameworkPropertyMetadata(false)); Window.WindowStyleProperty.OverrideMetadata(typeof(FloatingWindow), new FrameworkPropertyMetadata(WindowStyle.ToolWindow)); } public FloatingWindow() { this.Loaded += new RoutedEventHandler(OnLoaded); this.Unloaded += new RoutedEventHandler(OnUnloaded); this.SizeChanged += new SizeChangedEventHandler(FloatingWindow_SizeChanged); this.CommandBindings.Add(new CommandBinding(SetAsDockableWindowCommand, OnExecuteCommand, OnCanExecuteCommand)); this.CommandBindings.Add(new CommandBinding(SetAsFloatingWindowCommand, OnExecuteCommand, OnCanExecuteCommand)); this.CommandBindings.Add(new CommandBinding(TabbedDocumentCommand, OnExecuteCommand, OnCanExecuteCommand)); this.CommandBindings.Add(new CommandBinding(CloseCommand, OnExecuteCommand, OnCanExecuteCommand)); } void FloatingWindow_SizeChanged(object sender, SizeChangedEventArgs e) { if (HostedPane != null) { foreach (ManagedContent c in HostedPane.Items) c.FloatingWindowSize = new Size(Width, Height); ResizingPanel.SetEffectiveSize(HostedPane, new Size(Width, Height)); } } public FloatingWindow(DockingManager manager) : this() { //save manager ref _manager = manager; } DockingManager _manager = null; internal DockingManager Manager { get { return _manager; } } public FloatingDockablePane HostedPane { get { return (FloatingDockablePane)GetValue(ReferencedPaneProperty); } set { SetValue(ReferencedPaneProperty, value); } } // Using a DependencyProperty as the backing store for HostedPane. This enables animation, styling, binding, etc... public static readonly DependencyProperty ReferencedPaneProperty = DependencyProperty.Register("HostedPane", typeof(FloatingDockablePane), typeof(FlyoutPaneWindow)); internal virtual void OnEndDrag() { } internal virtual void OnShowSelectionBox() { } internal virtual void OnHideSelectionBox() { } #region Active Content Management ManagedContent lastActiveContent = null; protected override void OnActivated(EventArgs e) { if (Manager != null) { lastActiveContent = Manager.ActiveContent; Manager.ActiveContent = HostedPane.SelectedItem as ManagedContent; } base.OnActivated(e); } protected override void OnDeactivated(EventArgs e) { if (Manager != null && lastActiveContent != null) { Manager.ActiveContent = lastActiveContent; } base.OnDeactivated(e); } #endregion + #region IsClosing Flag Management + internal bool IsClosing { get; private set; } + + protected override void OnClosing(CancelEventArgs e) + { + IsClosing = true; + base.OnClosing(e); + } + + protected override void OnClosed(EventArgs e) + { + IsClosing = false; + base.OnClosed(e); + } + #endregion public abstract Pane ClonePane(); #region Non-Client area management protected const int WM_MOVE = 0x0003; protected const int WM_SIZE = 0x0005; protected const int WM_NCMOUSEMOVE = 0xa0; protected const int WM_NCLBUTTONDOWN = 0xA1; protected const int WM_NCLBUTTONUP = 0xA2; protected const int WM_NCLBUTTONDBLCLK = 0xA3; protected const int WM_NCRBUTTONDOWN = 0xA4; protected const int WM_NCRBUTTONUP = 0xA5; protected const int HTCAPTION = 2; protected const int SC_MOVE = 0xF010; protected const int WM_SYSCOMMAND = 0x0112; #region Load/Unload window events HwndSource _hwndSource; HwndSourceHook _wndProcHandler; protected void OnLoaded(object sender, EventArgs e) { WindowInteropHelper helper = new WindowInteropHelper(this); _hwndSource = HwndSource.FromHwnd(helper.Handle); _wndProcHandler = new HwndSourceHook(FilterMessage); _hwndSource.AddHook(_wndProcHandler); } protected void OnUnloaded(object sender, EventArgs e) { if (_hwndSource != null) _hwndSource.RemoveHook(_wndProcHandler); } #endregion protected virtual IntPtr FilterMessage( IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled ) { handled = false; if (Manager == null) return IntPtr.Zero; switch (msg) { case WM_SIZE: case WM_MOVE: //HostedPane.ReferencedPane.SaveFloatingWindowSizeAndPosition(this); break; case WM_NCLBUTTONDOWN: if (IsDockableWindow && wParam.ToInt32() == HTCAPTION) { short x = (short)((lParam.ToInt32() & 0xFFFF)); short y = (short)((lParam.ToInt32() >> 16)); Point clickPoint = this.TransformToDeviceDPI(new Point(x, y)); Manager.Drag(this, clickPoint, new Point(clickPoint.X - Left, clickPoint.Y - Top)); handled = true; } break; case WM_NCLBUTTONDBLCLK: if (IsDockableWindow && wParam.ToInt32() == HTCAPTION) { if (IsDockableWindow) { Redock(); handled = true; } } break; case WM_NCRBUTTONDOWN: if (wParam.ToInt32() == HTCAPTION) { short x = (short)((lParam.ToInt32() & 0xFFFF)); short y = (short)((lParam.ToInt32() >> 16)); ContextMenu cxMenu = FindResource(new ComponentResourceKey(typeof(DockingManager), ContextMenuElement.FloatingWindow)) as ContextMenu; if (cxMenu != null) { foreach (MenuItem menuItem in cxMenu.Items) menuItem.CommandTarget = this; cxMenu.Placement = PlacementMode.AbsolutePoint; cxMenu.PlacementRectangle = new Rect(new Point(x, y), new Size(0, 0)); cxMenu.PlacementTarget = this; cxMenu.IsOpen = true; } handled = true; } break; case WM_NCRBUTTONUP: if (wParam.ToInt32() == HTCAPTION) { handled = true; } break; } return IntPtr.Zero; } #endregion #region Floating/dockable window state bool _dockableWindow = true; public bool IsDockableWindow { get { return _dockableWindow; } set { _dockableWindow = value; if (_dockableWindow) { foreach (ManagedContent content in HostedPane.Items) if (content is DockableContent) ((DockableContent)content).SetStateToDockableWindow(); } else { foreach (ManagedContent content in HostedPane.Items) if (content is DockableContent) ((DockableContent)content).SetStateToFloatingWindow(); } } } public bool IsFloatingWindow { get { return !IsDockableWindow; } set { IsDockableWindow = !value; } } protected virtual void Redock() { } #endregion #region Commands private static object syncRoot = new object(); private static RoutedUICommand tabbedDocumentCommand = null; public static RoutedUICommand TabbedDocumentCommand { get { lock (syncRoot) { if (null == tabbedDocumentCommand) { tabbedDocumentCommand = new RoutedUICommand("T_abbed Document", "TabbedDocument", typeof(FloatingWindow)); } } return tabbedDocumentCommand; } } private static RoutedUICommand dockableCommand = null; public static RoutedUICommand SetAsDockableWindowCommand { get { lock (syncRoot) { if (null == dockableCommand) { dockableCommand = new RoutedUICommand("D_ockable", "Dockable", typeof(FloatingWindow)); } } return dockableCommand; } } private static RoutedUICommand floatingCommand = null; public static RoutedUICommand SetAsFloatingWindowCommand { get { lock (syncRoot) { if (null == floatingCommand) { floatingCommand = new RoutedUICommand("F_loating", "Floating", typeof(FloatingWindow)); } } return floatingCommand; } } private static RoutedUICommand closeCommand = null; public static RoutedUICommand CloseCommand { get { lock (syncRoot) { if (null == closeCommand) { closeCommand = new RoutedUICommand("Close", "Close", typeof(FloatingWindow)); } } return closeCommand; } } protected virtual void OnExecuteCommand(object sender, ExecutedRoutedEventArgs e) { if (e.Command == SetAsDockableWindowCommand) { IsDockableWindow = true; e.Handled = true; } else if (e.Command == SetAsFloatingWindowCommand) { IsFloatingWindow = true; e.Handled = true; } } protected virtual void OnCanExecuteCommand(object sender, CanExecuteRoutedEventArgs e) { if (e.Command == SetAsDockableWindowCommand) e.CanExecute = IsFloatingWindow; else if (e.Command == SetAsFloatingWindowCommand) e.CanExecute = IsDockableWindow; else e.CanExecute = true; } #endregion #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion } } diff --git a/AvalonDock/AvalonDock/FlyoutDockablePane.cs b/AvalonDock/AvalonDock/FlyoutDockablePane.cs index fd29864..a09404b 100644 --- a/AvalonDock/AvalonDock/FlyoutDockablePane.cs +++ b/AvalonDock/AvalonDock/FlyoutDockablePane.cs @@ -1,109 +1,111 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Input; namespace AvalonDock { internal class FlyoutDockablePane : DockablePane { static FlyoutDockablePane() { DockablePane.ShowTabsProperty.AddOwner(typeof(FlyoutDockablePane), new FrameworkPropertyMetadata(false)); } int _arrayIndexPreviousPane = -1; public FlyoutDockablePane() { } public FlyoutDockablePane(DockableContent content) { _referencedPane = content.ContainerPane as DockablePane; _manager = _referencedPane.GetManager(); //save current content position in container pane _arrayIndexPreviousPane = _referencedPane.Items.IndexOf(content); Anchor = _referencedPane.Anchor; SetValue(ResizingPanel.ResizeWidthProperty, new GridLength(ResizingPanel.GetEffectiveSize(_referencedPane).Width)); SetValue(ResizingPanel.ResizeHeightProperty, new GridLength(ResizingPanel.GetEffectiveSize(_referencedPane).Height)); //if (double.IsInfinity(ResizingPanel.GetResizeWidth(this))) // ResizingPanel.SetResizeWidth(this, 200); //if (double.IsInfinity(ResizingPanel.GetResizeHeight(this))) // ResizingPanel.SetResizeHeight(this, 200); //remove content from container pane //and add content to my temporary pane _referencedPane.Items.RemoveAt(_arrayIndexPreviousPane); this.Items.Add(content); //select the single content in this pane SelectedItem = this.Items[0]; } public override void OnApplyTemplate() { base.OnApplyTemplate(); } internal void RestoreOriginalPane() { if (this.Items.Count == 1) { _referencedPane.Items.Insert(_arrayIndexPreviousPane, RemoveContent(0)); ResizingPanel.SetResizeWidth(_referencedPane, ResizingPanel.GetResizeWidth(this)); ResizingPanel.SetResizeHeight(_referencedPane, ResizingPanel.GetResizeHeight(this)); } } DockablePane _referencedPane = null; DockingManager _manager = null; public override DockingManager GetManager() { return _manager; } internal override void ToggleAutoHide() { GetManager().ToggleAutoHide(_referencedPane); } - internal override void Close() - { - GetManager().Hide(SelectedItem as DockableContent); - } + //internal override void Close() + //{ + // DockingManager manager = GetManager(); + // if (manager != null) + // Manager.Hide(SelectedItem as DockableContent); + //} } } diff --git a/AvalonDock/AvalonDock/Pane.cs b/AvalonDock/AvalonDock/Pane.cs index 3e45173..9f06461 100644 --- a/AvalonDock/AvalonDock/Pane.cs +++ b/AvalonDock/AvalonDock/Pane.cs @@ -1,274 +1,289 @@ //Copyright (c) 2007-2009, Adolfo Marinucci //All rights reserved. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // //* Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. //* Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. //* Neither the name of Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Diagnostics; using System.Collections.Specialized; using System.ComponentModel; namespace AvalonDock { public abstract class Pane : System.Windows.Controls.Primitives.Selector, IDropSurface, IDockableControl, INotifyPropertyChanged { public Pane() { this.Loaded += new RoutedEventHandler(Pane_Loaded); this.Unloaded += new RoutedEventHandler(Pane_Unloaded); } void Pane_Loaded(object sender, RoutedEventArgs e) { //if (GetManager() == null && Parent != null) // throw new InvalidOperationException("Pane must be put under a DockingManager!"); AddDragPaneReferences(); } void Pane_Unloaded(object sender, RoutedEventArgs e) { RemoveDragPaneReferences(); } #region Contents management public bool HasSingleItem { get { return (bool)GetValue(HasSingleItemProperty); } protected set { SetValue(HasSingleItemPropertyKey, value); } } // Using a DependencyProperty as the backing store for HasSingleItem. This enables animation, styling, binding, etc... private static readonly DependencyPropertyKey HasSingleItemPropertyKey = DependencyProperty.RegisterReadOnly("HasSingleItem", typeof(bool), typeof(Pane), new PropertyMetadata(false)); public static readonly DependencyProperty HasSingleItemProperty = HasSingleItemPropertyKey.DependencyProperty; protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { HasSingleItem = (Items.Count == 1); if (Items.Count > 0) { int currentIndex = SelectedIndex; SelectedIndex = -1; if (currentIndex < 0 || currentIndex >= Items.Count) currentIndex = Items.Count - 1; SelectedIndex = currentIndex; } //else // RemoveDragPaneReferences(); base.OnItemsChanged(e); } //void RefreshContentsSelectedProperty() //{ // //foreach (ManagedContent mc in Items) // //{ // // //mc.IsSelected = (mc == SelectedItem); // // //Selector.SetIsSelected(mc // // if (Selector.GetIsSelected(mc)) // // mc.FocusContent(); // //} //} //protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) //{ // if (e.Property == SelectedItemProperty) // RefreshContentsSelectedProperty(); // // SetValue(ActiveContentProperty, SelectedItem); // //if (e.Property == ActiveContentProperty) // //{ // // //SetValue(SelectedItemProperty, ActiveContent); // //} // base.OnPropertyChanged(e); //} #endregion #region IDockableControl Members public virtual bool IsDocked { get { return true; } } #endregion public virtual DockingManager GetManager() { DependencyObject parent = LogicalTreeHelper.GetParent(this); while (parent != null && (!(parent is DockingManager))) parent = LogicalTreeHelper.GetParent(parent); return parent as DockingManager; } #region IDockableControl Members #endregion #region Membri di IDropSurface #region Drag pane services DockingManager _oldManager = null; //protected override void OnVisualParentChanged(DependencyObject oldParent) //{ // base.OnVisualParentChanged(oldParent); // RemoveDragPaneReferences(); // AddDragPaneReferences(); //} protected void RemoveDragPaneReferences() { if (_oldManager != null) { _oldManager.DragPaneServices.Unregister(this); _oldManager = null; } } protected void AddDragPaneReferences() { { _oldManager = GetManager(); if (_oldManager != null) _oldManager.DragPaneServices.Register(this); } } #endregion public abstract bool IsSurfaceVisible {get;} public virtual Rect SurfaceRectangle { get { if (!IsSurfaceVisible) return new Rect(); if (PresentationSource.FromVisual(this) == null) return new Rect(); return new Rect(HelperFunc.PointToScreenWithoutFlowDirection(this, new Point()), new Size(ActualWidth, ActualHeight)); } } public virtual void OnDragEnter(Point point) { GetManager().OverlayWindow.ShowOverlayPaneDockingOptions(this); } public virtual void OnDragOver(Point point) { } public virtual void OnDragLeave(Point point) { GetManager().OverlayWindow.HideOverlayPaneDockingOptions(this); } public virtual bool OnDrop(Point point) { return false; } #endregion public virtual ManagedContent RemoveContent(int index) { ManagedContent contentToRemove = Items[index] as ManagedContent; Items.RemoveAt(index); return contentToRemove; } protected FrameworkElement _partHeader = null; public override void OnApplyTemplate() { base.OnApplyTemplate(); //gets a reference to the header for the pane _partHeader = GetTemplateChild("PART_Header") as FrameworkElement; } internal virtual ResizingPanel GetContainerPanel() { return LogicalTreeHelper.GetParent(this) as ResizingPanel; } + /// <summary> + /// Closes or hides provided content depending on HideOnClose property + /// </summary> + internal virtual void CloseOrHide(DockableContent cntToCloseOrHide) + { + Debug.Assert(cntToCloseOrHide != null); + + DockingManager manager = GetManager(); + if (cntToCloseOrHide.HideOnClose && manager != null) + manager.Hide(cntToCloseOrHide); + else + RemoveContent(Items.IndexOf(cntToCloseOrHide)); + } + + #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion } } diff --git a/AvalonDock/AvalonDock/Properties/AssemblyInfo.cs b/AvalonDock/AvalonDock/Properties/AssemblyInfo.cs index a02faba..83b153e 100644 --- a/AvalonDock/AvalonDock/Properties/AssemblyInfo.cs +++ b/AvalonDock/AvalonDock/Properties/AssemblyInfo.cs @@ -1,62 +1,62 @@ #region Using directives using System.Reflection; using System.Runtime.CompilerServices; using System.Resources; using System.Globalization; using System.Windows; using System.Runtime.InteropServices; #endregion // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AvalonDock")] [assembly: AssemblyDescription("WPF docking library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AvalonDock")] [assembly: AssemblyCopyright("Copyright @ Adolfo Marinucci 2007-2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] // Specifies the location in which theme dictionaries are stored for types in an assembly. [assembly: ThemeInfo( // Specifies the location of system theme-specific resource dictionaries for this project. // The default setting in this project is "None" since this default project does not // include these user-defined theme files: // Themes\Aero.NormalColor.xaml // Themes\Classic.xaml // Themes\Luna.Homestead.xaml // Themes\Luna.Metallic.xaml // Themes\Luna.NormalColor.xaml // Themes\Royale.NormalColor.xaml ResourceDictionaryLocation.SourceAssembly, // Specifies the location of the system non-theme specific resource dictionary: // Themes\generic.xaml ResourceDictionaryLocation.SourceAssembly)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: -[assembly: AssemblyVersion("1.2.2641")] +[assembly: AssemblyVersion("1.2.2648")]
icsharpcode/SharpDevelop-Vendor
aab4db6c8b3d566444bd445f5c6ad030adc1b5bb
Add 'UsageDataCollector' AddIn.
diff --git a/SQLite/SQLite-1.0.65.0-source.zip b/SQLite/SQLite-1.0.65.0-source.zip new file mode 100644 index 0000000..0c5830b Binary files /dev/null and b/SQLite/SQLite-1.0.65.0-source.zip differ
icsharpcode/SharpDevelop-Vendor
dcef0b0a5c900500c590e1c326bdd8a7169a0f13
Vendor/Graphviz - used in Object graph debugger visualizer.
diff --git a/Graphviz/graphviz-src-2.22.2.tar.gz b/Graphviz/graphviz-src-2.22.2.tar.gz new file mode 100644 index 0000000..b65c364 Binary files /dev/null and b/Graphviz/graphviz-src-2.22.2.tar.gz differ diff --git a/Graphviz/graphviz2.22.zip b/Graphviz/graphviz2.22.zip new file mode 100644 index 0000000..288c7e2 Binary files /dev/null and b/Graphviz/graphviz2.22.zip differ
icsharpcode/SharpDevelop-Vendor
9a99a36e6737f00d4c57099f4b0cc1d4b7bffd44
Host option panels in WPF window, allow WPF option panels.
diff --git a/AvalonDock/AvalonDock 1.1.1648.zip b/AvalonDock/AvalonDock 1.1.1648.zip deleted file mode 100644 index 2c591a0..0000000 Binary files a/AvalonDock/AvalonDock 1.1.1648.zip and /dev/null differ diff --git a/AvalonDock/AvalonDock 1.1.1692.zip b/AvalonDock/AvalonDock 1.1.1692.zip new file mode 100644 index 0000000..3679bcd Binary files /dev/null and b/AvalonDock/AvalonDock 1.1.1692.zip differ
icsharpcode/SharpDevelop-Vendor
15d1eb70eb2705bd39bbd04b28bf68f4d27910b6
Add log4net, NUnit, PartCover source code to Vendor.
diff --git a/NUnit/NUnit-2.4.7-src.zip b/NUnit/NUnit-2.4.7-src.zip new file mode 100644 index 0000000..d51484e Binary files /dev/null and b/NUnit/NUnit-2.4.7-src.zip differ diff --git a/PartCover/PartCover-.NET-2.2-src.zip b/PartCover/PartCover-.NET-2.2-src.zip new file mode 100644 index 0000000..e00c756 Binary files /dev/null and b/PartCover/PartCover-.NET-2.2-src.zip differ diff --git a/log4net/log4net-1.2.10-src.zip b/log4net/log4net-1.2.10-src.zip new file mode 100644 index 0000000..9a6067c Binary files /dev/null and b/log4net/log4net-1.2.10-src.zip differ
icsharpcode/SharpDevelop-Vendor
6b840917ed4866a223dd080d6c5f2ff1880ac4bf
Upload SvnDotNet source code
diff --git a/SvnDotNet/subversion-1.5.0.zip b/SvnDotNet/subversion-1.5.0.zip new file mode 100644 index 0000000..7b88212 Binary files /dev/null and b/SvnDotNet/subversion-1.5.0.zip differ diff --git a/SvnDotNet/svn-win32-libintl.zip b/SvnDotNet/svn-win32-libintl.zip new file mode 100644 index 0000000..29c89ca Binary files /dev/null and b/SvnDotNet/svn-win32-libintl.zip differ diff --git a/SvnDotNet/svndotnet.zip b/SvnDotNet/svndotnet.zip new file mode 100644 index 0000000..69c6485 Binary files /dev/null and b/SvnDotNet/svndotnet.zip differ diff --git a/SvnDotNet/zlib-1.2.3.tar.gz b/SvnDotNet/zlib-1.2.3.tar.gz new file mode 100644 index 0000000..c222de1 Binary files /dev/null and b/SvnDotNet/zlib-1.2.3.tar.gz differ
icsharpcode/SharpDevelop-Vendor
cd96b7ba7a5823033b1a63391f683765d81fbf6d
Upload SvnDotNet source code
diff --git a/SvnDotNet/openssl-0.9.8h.tar.gz b/SvnDotNet/openssl-0.9.8h.tar.gz new file mode 100644 index 0000000..12c7fc0 Binary files /dev/null and b/SvnDotNet/openssl-0.9.8h.tar.gz differ diff --git a/SvnDotNet/subversion-deps-1.5.0.zip b/SvnDotNet/subversion-deps-1.5.0.zip new file mode 100644 index 0000000..dbd7449 Binary files /dev/null and b/SvnDotNet/subversion-deps-1.5.0.zip differ
icsharpcode/SharpDevelop-Vendor
ad3dd934e0dfddf3327f396d1fb8ecb06321df6b
Upload SvnDotNet source code
diff --git a/SvnDotNet/db-4.4.20.tar.gz b/SvnDotNet/db-4.4.20.tar.gz new file mode 100644 index 0000000..ccf8be1 Binary files /dev/null and b/SvnDotNet/db-4.4.20.tar.gz differ
icsharpcode/SharpDevelop-Vendor
0903e02b2324c9442e78d471fdd65a7211604623
Add "Vendor" directory. Make WpfDesigner GetBitmapExtension.ProvideValue thread-safe. Make FileUtility.IsBaseDirectory more efficient.
diff --git a/Readme.txt b/Readme.txt new file mode 100644 index 0000000..051fc18 --- /dev/null +++ b/Readme.txt @@ -0,0 +1,4 @@ +This directory contains the source code of other open-source projects used by SharpDevelop. +Projects used by SharpDevelop in binary form only are here as compressed archives (might be useful if some project disappears or becomes commercial, e.g. NCover). +Projects used by SharpDevelop in (modified) source form are here in unpacked, unmodified form. This allows merging changes between vendor releases into our modified version. +
stm555/tablegeeks
5ca4fc3c017724447232f28a648861f6ea379fb2
First attempt at a front end and added ability to save sessions and campaigns
diff --git a/application/bootstrap.php b/application/bootstrap.php index 6e03089..c27d554 100644 --- a/application/bootstrap.php +++ b/application/bootstrap.php @@ -1,46 +1,60 @@ -<?php +<?php +//define the application path for use later +define('APPLICATION_PATH', dirname(__FILE__)); + // ** Check to see if the environment is already setup ** if (isset($bootstrap) && $bootstrap) { // Enable all errors so we'll know when something goes wrong. error_reporting(E_ALL | E_STRICT); ini_set('display_startup_errors', 1); ini_set('display_errors', 1); // Add our {{library}} directory to the include path so that PHP can find the Zend Framework classes. // you may wish to add other paths here, or keep system paths: set_include_path('../library' . PATH_SEPARATOR . get_include_path() - set_include_path('../library' . PATH_SEPARATOR . realpath(dirname(__FILE__).'/../') . PATH_SEPARATOR . get_include_path()); + set_include_path(APPLICATION_PATH . '/models' . PATH_SEPARATOR . APPLICATION_PATH . '/../library' . PATH_SEPARATOR . get_include_path()); // Set up autoload. // This is a nifty trick that allows ZF to load classes automatically so that you don't have to litter your // code with 'include' or 'require' statements. require_once "Zend/Loader.php"; Zend_Loader::registerAutoload(); } // ** Get the front controller ** // The Zend_Front_Controller class implements the Singleton pattern, which is a design pattern used to ensure // there is only one instance of Zend_Front_Controller created on each request. $frontController = Zend_Controller_Front::getInstance(); // Point the front controller to your action controller directory. -$frontController->setControllerDirectory('../application/controllers'); - +$frontController->setControllerDirectory(APPLICATION_PATH . '/controllers'); + +// Set up Layout +Zend_Layout::startMvc(APPLICATION_PATH . '/views/layouts'); +// Set default doctype +$view = Zend_Layout::getMvcInstance()->getView(); +$view->doctype('XHTML1_STRICT'); +$view->headLink()->appendStylesheet('/style/default_layout.css'); +$view->addHelperPath(APPLICATION_PATH . '/views/helpers','Tg_View_Helper'); +//remove $view from global +unset($view); + + // ** Load and register Basic Configuration File ** -$config = new Zend_Config_Xml( dirname( __FILE__ ) . '/configs/tablegeeks.xml' ); +$config = new Zend_Config_Xml( APPLICATION_PATH . '/configs/tablegeeks.xml' ); Zend_Registry::set( 'config', $config ); // ** Initialize Logging $log = new Zend_Log( new Zend_Log_Writer_Firebug( ) ); Zend_Registry::set( 'log', $log ); // ** Load and register db access $profiler = new Zend_Db_Profiler_Firebug( 'All DB Queries' ); $db = Zend_Db::factory( $config->db->connection ); $profiler->setEnabled( $config->db->profiler->enabled ); $db->setProfiler( $profiler ); Zend_Registry::set( 'db', $db ); Zend_Db_Table_Abstract::setDefaultAdapter( $db ); $frontController->throwExceptions(true); diff --git a/application/controllers/IndexController.php b/application/controllers/IndexController.php index 9928722..7344033 100644 --- a/application/controllers/IndexController.php +++ b/application/controllers/IndexController.php @@ -1,24 +1,21 @@ <?php class IndexController extends Zend_Controller_Action { public function init() { /* Initialize action controller here */ } public function indexAction() { - require_once dirname( __file__ ) . '/../models/Session/Db/Mysql/Table.php'; - $sessionTable = new Tg_Session_Db_MySql_Table( ); - Zend_Registry::get( 'log' )->debug( Zend_Debug::dump( $sessionTable->find( 1 )), 'Tuple from Session', false ); } } diff --git a/application/controllers/PodcastController.php b/application/controllers/PodcastController.php index 87724bb..3ea6182 100644 --- a/application/controllers/PodcastController.php +++ b/application/controllers/PodcastController.php @@ -1,33 +1,31 @@ <?php -require_once 'application/models/Session.php'; +require_once 'Session.php'; /** * PodcastController * * @author stm */ class PodcastController extends Zend_Controller_Action { public function init() { /* Initialize action controller here */ } /** * indexAction * * @return void */ public function indexAction() { $log = Zend_Registry::get( 'log' ); $log->info( 'index action of Podcast controller' ); $sessions = Tg_Session::fetchAll( ); - //FIXME need to use a project defined base path here .. - $viewHelpersPath = realpath(dirname(__FILE__) . '/../views/helpers'); - $this->view->addHelperPath($viewHelpersPath,'Tg_View_Helper'); - $this->view->sessions = $sessions; - $this->_helper->viewRenderer->setViewSuffix('pxml'); + $this->view->sessions = $sessions; + $this->_helper->layout->disableLayout(); + $this->_helper->viewRenderer->setViewSuffix('pxml'); } } diff --git a/application/models/Campaign.php b/application/models/Campaign.php index b8df78e..8f23448 100644 --- a/application/models/Campaign.php +++ b/application/models/Campaign.php @@ -1,48 +1,149 @@ <?php class Tg_Campaign { /** * unique campaign id * * @var integer */ public $id; /** * Campaign Name * * @var string */ public $name = ''; /** * Data access through table gateway pattern * * @var Zend_Db_Table_Abstract */ protected $_campaignTable; + + /** + * Data access through the table row pattern + * + * @var Zend_Db_Table_Row_Abstract + **/ + protected $_campaignRow; + + /** + * Form + * + * @var Zend_Form + */ + protected $_campaignForm; private function _getCampaignTable( ) { if ( is_null( $this->_campaignTable ) ) { require_once ( dirname( __FILE__ ) . '/Campaign/Db/MySql/CampaignTable.php'); $this->_campaignTable = new Tg_Campaign_Db_MySql_CampaignTable( ); } return $this->_campaignTable; } //Static methods - public static function fetch( $id ) + public static function fetch( $id = null ) { $campaign = new Tg_Campaign( ); + + if (is_null($id)) { + return $campaign; + } + $campaignTable = $campaign->_getCampaignTable( ); $rowset = $campaignTable->find( $id ); - $row = $rowset->current( ); - $campaign->id = $row->id; - $campaign->name = $row->name; + $campaign->load( $rowset->current( ) ); return $campaign; } + + public function load( $data ) { + if ( $data instanceof Zend_Form ) { + return $this->_loadFromForm( $data ); + } + //TODO load from row + if ( $data instanceof Zend_Db_Table_Row ) { + return $this->_loadFromRow( $data ); + } + //TODO load from array + throw new Exception('Can not load Campaign: invalid type'); + } + + private function _loadFromForm( Zend_Form $form ) { + $this->id = $form->id->getValue(); + $this->name = $form->name->getValue(); + + $this->_campaignForm = $form; + } + + private function _loadFromRow ( Zend_Db_Table_Row $row ) { + $this->id = $row->id; + $this->name = $row->name; + + $this->_campaignRow = $row; + } + + public function getForm( $includeSubmit = false) { + if ($this->_campaignForm instanceof Zend_Form) { + $form = $this->_campaignForm; + } else { + $form = new Zend_Form(); + $form->setIsArray(true); + $form->addElement('hidden', 'id'); + $form->addElement('text','name', array('label' => 'Campaign')); + $nameField = $form->getelement('name'); + $nameField->setRequired(true); + + $this->_campaignForm = $form; + $this->_populateForm(); + $form = $this->_campaignForm; + } + + if ($includeSubmit) { + $form->addElement('submit', 'submit'); + } + + return $form; + } + + private function _populateForm() { + //initialize object form if necessary + if (is_null($this->_campaignForm)) { + $this->getForm(); + return; + } + if (!is_null($this->id)) { + $this->_campaignForm->id->setValue($this->id); + $this->_campaignForm->name->setValue($this->name); + } + } + + private function _getRow() { + if ( $this->_campaignRow instanceof Zend_Db_Table_Row ) { + $row = $this->_campaignRow; + } else { + $row = $this->_getCampaignTable()->createRow(); + } + + $row->id = $this->id; + $row->name = $this->name; + + $this->_campaignRow = $row; + + return $row; + } + + public function save() { + //TODO see if an existing campaign all ready exists to reuse + $row = $this->_getRow(); + $row->save(); + //reload from row to get ids + $this->load( $row ); + } } diff --git a/application/models/Media.php b/application/models/Media.php index 569dc9d..a2077ad 100644 --- a/application/models/Media.php +++ b/application/models/Media.php @@ -1,102 +1,150 @@ <?php /** * Tg_Media * * @author stm */ class Tg_Media { const DURATION_TYPE_SECONDS = 0; const DURATION_TYPE_MINUTES = 1; const DURATION_TYPE_HOURS = 2; /** * unique media id * * @var integer */ public $id; /** * local relative path to media file * * @var string */ public $path =''; /** * size of media file * * @var int */ public $size = 0; /** * mimetype of media file * * @var string */ public $mimetype = ''; /** * duration in seconds of media * * @var int */ public $duration = 0; /** * Data access through table gateway pattern * * @var Zend_Db_Table_Abstract */ protected $_mediaTable; + + /** + * Form + * + * @var Zend_Form + */ + protected $_mediaForm; private function _getMediaTable( ) { if ( is_null( $this->_mediaTable ) ) { require_once ( dirname( __FILE__ ) . '/Media/Db/MySql/MediaTable.php'); $this->_mediaTable = new Tg_Media_Db_MySql_MediaTable( ); } return $this->_mediaTable; } //Static methods - public static function fetch( $id ) + public static function fetch( $id = null ) { $media = new Tg_Media( ); + if ( is_null( $id ) ) { + return $media; + } $mediaTable = $media->_getMediaTable( ); $rowset = $mediaTable->find( $id ); $row = $rowset->current( ); $media->id = $row->id; $media->path = $row->path; $media->size = $row->size; $media->mimetype = $row->mimetype; $media->duration = $row->duration; return $media; } /** * getDuration returns a string formatted duration based on the unit * * @param int $unit * @return string */ public function getDuration( $unit = self::DURATION_TYPE_SECONDS ) { switch ( $unit ) { case self::DURATION_TYPE_SECONDS: //seconds return (string)$this->duration; case self::DURATION_TYPE_MINUTES: //minutes //seconds return floor( $this->duration / 60 ) . ':' . $this->duration % 60; case self::DURATION_TYPE_HOURS: //hours //minutes //seconds return floor ( $this->duration / ( 60*60 ) ) . ':' . floor( $this->duration / 60 ) % 60 . ':' . $this->duration % 60; default: throw new Exception( 'Invalid duration unit' ); } } + + //todo update this form to use a file upload field + public function getForm( $includeSubmit = false) { + if ($this->_mediaForm instanceof Zend_Form) { + $form = $this->_mediaForm; + } else { + $form = new Zend_Form(); + $form->setIsArray(true); + $form->addElement('hidden', 'id'); + $form->addElement('text','name', array('label' => 'media')); + + $this->_mediaForm = $form; + $this->_populateForm(); + $form = $this->_mediaForm; + } + + if ($includeSubmit) { + $form->addElement('submit', 'submit'); + } + + return $form; + } + //TODO update this form as appropriate + private function _populateForm() { + //initialize object form if necessary + if (is_null($this->_mediaForm)) { + $this->getForm(); + return; + } + if (!is_null($this->id)) { + $this->_mediaForm->id->setValue($this->id); + $this->_mediaForm->name->setValue($this->name); + } + } + + //TODO implement this + public function save() { + } } diff --git a/application/models/Session.php b/application/models/Session.php index 0f891fd..aee09f4 100644 --- a/application/models/Session.php +++ b/application/models/Session.php @@ -1,155 +1,326 @@ <?php require_once 'User.php'; require_once 'Campaign.php'; require_once 'Media.php'; /** * Tg_Session * * @author stm */ class Tg_Session { /** * unique session id * * @var integer */ public $id; /** * Campaign that this session part of * @var Tg_Campaign **/ public $campaign; /** * Stores date of the session * @var Zend_Date **/ public $date; /** * User who uploaded this session * @var Tg_User **/ public $author; /** * Description of this session * @var string **/ public $description = ''; /** * Synopsis of this session * @var string **/ public $synopsis = ''; /** * Media file for this session * @var Tg_Media **/ public $media; /** * Date that this session was added * @var Zend_Date **/ public $addDate; /** * Collection of tags related to this session * @var array **/ public $tags = array(); /** * Data access through table gateway pattern * * @var Zend_Db_Table_Abstract */ protected $_sessionTable; + + /** + * Data access through table gateway row + * + * @var Zend_Db_Table_Row_Abstract + **/ + protected $_sessionRow; /** * Data access through table gateway pattern for tags * * @var Zend_Db_Table_Abstract */ protected $_tagTable; + + /** + * Form definition w/ validators + * @var Zend_Form + **/ + protected $_sessionForm; private function _getSessionTable( ) { if ( is_null( $this->_sessionTable ) ) { require_once ( dirname( __FILE__ ) . '/Session/Db/MySql/SessionTable.php'); $this->_sessionTable = new Tg_Session_Db_MySql_SessionTable( ); } return $this->_sessionTable; } private function _getTagTable( ) { if ( is_null( $this->_tagTable ) ) { require_once ( dirname( __FILE__ ) . '/Tag/Db/MySql/TagTable.php'); $this->_tagTable = new Tg_Tag_Db_MySql_TagTable( ); } return $this->_tagTable; } + + public function getForm( $includeSubmit = false) { + if ($this->_sessionForm instanceof Zend_Form) { + $form = $this->_sessionForm; + } else { + $form = new Zend_Form(); + $form->setIsArray(true); + $form->addElement('hidden', 'id'); + $form->addSubForm($this->campaign->getForm(), 'campaign'); + $form->addElement('text', 'date', array('label' => 'Date')); + $form->addElement('text', 'description', array('label' => 'Description')); + $form->addElement('text', 'synopsis', array('label' => 'Synopsis')); + $form->addElement('text', 'tags', array('label' => 'Tags')); + + $this->_sessionForm = $form; + $this->_populateForm(); + $form = $this->_sessionForm; + } + + if ($includeSubmit) { + $form->addElement('submit', 'submit'); + } + + return $form; + } + + private function _populateForm() { + //initialize object form if necessary + if (is_null($this->_sessionForm)) { + $this->getForm(); + return; + } + if (!is_null($this->id)) { + $this->_sessionForm->id->setValue($this->id); + $this->_sessionForm->date->setValue((string)$this->date); + $this->_sessionForm->description->setValue($this->description); + $this->_sessionForm->synopsis->setValue($this->synopsis); + $this->_sessionForm->tags->setValue(implode(',',$this->tags)); + } + } - private function _loadFromRow( Zend_Db_Table_Row $row ) + /** + * Loads the object from the given data + * @param mixed $data a row or form object + * @param boolean $populateTags Whether to overload the tags, only applies to row objects + * @throws Exception + **/ + public function load( $data, $populateTags = true ) { + if ( $data instanceof Zend_Db_Table_Row ) { + return $this->_loadFromRow( $data, $populateTags ); + } + if ($data instanceof Zend_Form ) { + return $this->_loadFromForm( $data ); + } + //TODO load from array + //data not in acceptable form + throw new Exception('Can not load session: invalid type'); + } + + private function _loadFromForm( Zend_Form $form ) { + $sessionId = $form->id->getValue(); + if ( !empty( $sessionId ) ) { + $this->id = $sessionId; + } + $campaignId = $form->campaign->id->getValue(); + if ( !empty( $campaignId ) ) { + $this->campaign = Tg_Campaign::fetch( $campaignId ); + } else { + $this->campaign = Tg_Campaign::fetch( ); + } + $this->campaign->load( $form->campaign ); + $this->date = new Zend_Date( $form->date->getValue() ); + $this->description = $form->description->getValue(); + $this->synopsis = $form->synopsis->getValue(); + //todo media + //todo author + $this->tags = explode( ',', $form->tags->getValue() ); + + $this->_sessionForm = $form; + } + + private function _loadFromRow( Zend_Db_Table_Row $row, $populateTags = true ) { $this->id = $row->id; $this->description = $row->description; $this->synopsis = $row->synopsis; $this->date = new Zend_Date( $row->date ); $this->campaign = Tg_Campaign::fetch( $row->campaign ); $this->author = Tg_User::fetch( $row->author ); $this->media = Tg_Media::fetch( $row->media ); - $this->_populateTags( ); + if ( $populateTags ) { + $this->_populateTags( ); + } + $this->_sesseionRow = $row; } private function _populateTags( ) { $tagTable = $this->_getTagTable( ); $select = $tagTable->select() ->setIntegrityCheck(false) ->from( $tagTable, 'tag' ) ->joinInner( 'tags_xref', 'tags.id = tags_xref.tag', array( ) ) ->where( "tags_xref.type = ?", Tg_Tag_Db_MySql_TagTable::TYPE_SESSION ) ->where( "tags_xref.entity = ?", $this->id ); Zend_Registry::get( 'log' )->debug( $select->assemble() ); - $this->tags = $tagTable->getAdapter( )->fetchCol( $select ); + $this->tags = array_merge( $this->tags, $tagTable->getAdapter( )->fetchCol( $select ) ); + } + + public function save( ) { + $this->campaign->save(); + $this->media->save(); + $this->author->save(); + $row = $this->_getRow(); + $row->save(); + //reload from row to get new ids (don't override tags) + $this->load( $row, false ); + $this->_saveTags(); + } + + private function _saveTags() { + $tagTable = $this->_getTagTable(); + $adapter = $tagTable->getAdapter(); + $tags = array_flip($this->tags); + $tagSet = ( !empty( $this->tags ) ) ? "('" . implode( "','", $this->tags ) . "')" : "()"; + $xrefJoin = "tags.id = tags_xref.tag AND tags_xref.type = " . $adapter->quote('session') . " and tags_xref.entity = " . $adapter->quote($this->id, Zend_Db::INT_TYPE); + $select = $tagTable->select() + ->setIntegrityCheck(false) + ->from( $tagTable, array( 'id', 'tag' ) ) + ->joinLeft( 'tags_xref', $xrefJoin, 'entity') + ->where( "tags.tag IN $tagSet" ) + ->orWhere( "tags_xref.entity = ?", $this->id, Zend_Db::INT_TYPE ); + Zend_Registry::get('log')->debug( (string)$select ); + $existingTagsResult = $adapter->query( $select ); + $existingTagsResult->setFetchMode(Zend_Db::FETCH_OBJ); + while ( $row = $existingTagsResult->fetch() ) { + if ( is_null($row->entity) ) { + //add the missing tag connection + $adapter->insert('tags_xref', array('tag' => $row->id, 'type' => 'session', 'entity' => $this->id, 'created' => new Zend_Db_Expr( 'NOW()' ) ) ); + } + if ( isset( $tags[$row->tag] ) ) { + unset( $tags[$row->tag] ); + } else { + //remove the new unused tag connection + $adapter->delete( 'tags_xref', "tag = " . $adapter->quote( $row->id, Zend_Db::INT_TYPE ) . + " AND type = " . $adapter->quote('session') . + " AND entity = " . $adapter->quote( $this->id, Zend_Db::INT_TYPE ) ); + } + } + foreach ( $tags as $newTag => $placeHolder) { + //create the new tag and connection + $tagId = $adapter->insert( 'tags', array( 'tag' => $newTag, 'created' => new Zend_Db_Expr( 'NOW()' ) ) ); + $adapter->insert('tags_xref', array('tag' => $tagId, 'type' => 'session', 'entity' => $this->id, 'created' => new Zend_Db_Expr( 'NOW()' ) ) ); + } + } + + private function _getRow() { + if ($this->_sessionRow instanceof Zend_Db_Table_Row_Abstract ) { + $row = $this->_sessionRow; + } else { + $row = $this->_getSessionTable()->createRow(); + } + $row->campaign = $this->campaign->id; + $row->description = $this->description; + $row->synopsis = $this->synopsis; + //TODO add date format correctly + $row->date = (string)$this->date; + $row->media = $this->media->id; + $row->author = $this->author->id; + + return $row; } //Static methods /** * fetch a gaming session by id * * @param integer $id * @return Tg_Session */ - public static function fetch( $id ) + public static function fetch( $id = null ) { $session = new Tg_Session( ); + + if ( is_null($id) ) { + $session->campaign = Tg_Campaign::fetch(); + $session->author = Tg_User::fetch(); + $session->media = Tg_Media::fetch(); + return $session; + } + $sessionTable = $session->_getSessionTable( ); $rowset = $sessionTable->find( $id ); - $session->_loadFromRow( $rowset->current( ) ); + if (is_null($rowset->current())) { + throw new Exception('Invalid Session Id'); + } + $session->load( $rowset->current( ) ); return $session; } /** * Gets all gaming sessions and returns them in an array * * @return array */ public static function fetchAll( ) { $session = new Tg_Session( ); $sessionTable = $session->_getSessionTable( ); $rowset = $sessionTable->fetchAll( ); $sessions = array( ); foreach( $rowset as $row ) { $session = new Tg_Session( ); $session->_loadFromRow( $row ); $sessions[] = $session; } return $sessions; } } diff --git a/application/models/User.php b/application/models/User.php index 4bec030..9452ad1 100644 --- a/application/models/User.php +++ b/application/models/User.php @@ -1,54 +1,60 @@ <?php /** * Tg_User * * @author stm */ class Tg_User { /** * unique user id * * @var integer */ public $id; /** * User's common name * * @var string */ public $name; /** * Data access through table gateway pattern * * @var Zend_Db_Table_Abstract */ protected $_userTable; private function _getUserTable( ) { if ( is_null( $this->_userTable ) ) { require_once ( dirname( __FILE__ ) . '/User/Db/MySql/UserTable.php'); $this->_userTable = new Tg_User_Db_MySql_UserTable( ); } return $this->_userTable; } + public function save() { + //TODO implement this + } + //Static methods - public static function fetch( $id ) + public static function fetch( $id = null ) { $user = new Tg_User( ); + if ( is_null($id) ) { + return $user; + } $userTable = $user->_getUserTable( ); $rowset = $userTable->find( $id ); $row = $rowset->current( ); $user->id = $row->id; $user->name = $row->name; return $user; } - } diff --git a/application/views/helpers/PodcastUrl.php b/application/views/helpers/PodcastUrl.php index 848364b..58d6aac 100644 --- a/application/views/helpers/PodcastUrl.php +++ b/application/views/helpers/PodcastUrl.php @@ -1,17 +1,17 @@ <?php class Tg_View_Helper_PodcastUrl extends Zend_View_Helper_Abstract { /** * Takes a local path to a podcast file and converts it into a valid url - * - * @TODO user of the SERVER_NAME super global is probably a security hole -- switch to configuration value + * + * @TODO user of the SERVER_NAME super global is probably a security hole -- switch to configuration value * * @param string $filePath Path to podcast audio file * @return string * @author stm **/ public function podcastUrl($filePath) { - return "http://{$_SERVER['SERVER_NAME']}/audio/12345.m4a"; + return "http://{$_SERVER['SERVER_NAME']}" . $this->view->baseUrl() . "/audio/12345.m4a"; } } diff --git a/application/views/scripts/index/index.phtml b/application/views/scripts/index/index.phtml index 8ce2407..ce7c146 100644 --- a/application/views/scripts/index/index.phtml +++ b/application/views/scripts/index/index.phtml @@ -1 +1,2 @@ -Hello from the index view script. \ No newline at end of file +<h1>TableGeeks</h1> +<p>TableGeeks gathers your gaming sessions as podcasts. <a href="<?= $this->baseUrl() . '/session/new' ?>">Submit your recording now!</a></p> \ No newline at end of file diff --git a/tests/models/CampaignTest.php b/tests/models/CampaignTest.php index b7cc004..3cda122 100644 --- a/tests/models/CampaignTest.php +++ b/tests/models/CampaignTest.php @@ -1,47 +1,57 @@ <?php require_once( dirname( __FILE__ ) . '/../TestHelper.php' ); require_once( 'PHPUnit/Framework.php' ); require_once( 'Campaign.php' ); require_once( Zend_Registry::get( 'testBootstrap' ) ); class CampaignTest extends PHPUnit_Framework_TestCase { public function setUp( ) { //load database with test data } public function tearDown( ) { //remove test data } public function testFetchGetsAGamingCampaign( ) { $campaign = Tg_Campaign::fetch( 9999 ); $this->assertType( 'Tg_Campaign', $campaign ); } public function testFetchThrowsExceptionOnNonExistantGamingSession( ) { try { $campaign = Tg_Campaign::fetch( 99999999 ); } catch ( Exception $e ) { return; //exception thrown, pass } $this->fail( ); //exception not thrown, fail } public function testFetchGetsGamingCampaignById( ) { $campaignId = 9999; $campaignName = 'Grand Campaign'; $campaign = Tg_Campaign::fetch( $campaignId ); $this->assertEquals($campaignId, $campaign->id ); $this->assertEquals( $campaignName, $campaign->name ); } + + public function testSaveShouldPersistData() { + $campaign = Tg_Campaign::fetch( ); + $campaign->name = "Some Campaign!"; + $campaign->save(); + + $fetchedCampaign = Tg_Campaign::fetch( $campaign->id ); + $this->assertEquals($campaign->id, $fetchedCampaign->id); + $this->assertEquals($campaign->name, $fetchedCampaign->name); + } } diff --git a/tests/models/SessionTest.php b/tests/models/SessionTest.php index 7fc03b5..fd1b941 100644 --- a/tests/models/SessionTest.php +++ b/tests/models/SessionTest.php @@ -1,103 +1,153 @@ <?php require_once( dirname( __FILE__ ) . '/../TestHelper.php' ); require_once( 'PHPUnit/Framework.php' ); require_once( 'Session.php' ); require_once( Zend_Registry::get( 'testBootstrap' ) ); /** * SessionTest * @TODO refactor all these hard coded test values to defines or something * @TODO need to add support for tags * @author stm */ class SessionTest extends PHPUnit_Framework_TestCase { + const TEST_SESSION_ID = 9999; + const TEST_SESSION_ID_INVALID = 99999999; + const TEST_CAMPAIGN_ID = 9999; + const TEST_CAMPAIGN_NAME = 'Grand Campaign'; + const TEST_MEDIA_ID = 9999; + const TEST_AUTHOR_ID = 9999; + public function setUp( ) { //load database with test data } public function tearDown( ) { //empty out all test data } public function testFetchNonExistantThrowsException( ) { try { - $session = Tg_Session::fetch( 999999 ); + $session = Tg_Session::fetch( self::TEST_SESSION_ID_INVALID ); } catch ( Exception $e ) { return; //exception thrown, pass } $this->fail( ); //exception not thrown, fail } public function testFetchGetsAGamingSession( ) { - $session = Tg_Session::fetch( 9999 ); + $session = Tg_Session::fetch( self::TEST_CAMPAIGN_ID ); $this->assertType( 'Tg_Session', $session ); } public function testFetchGetsGamingSessionByIdShouldHavePrimitiveValues( ) { - $sessionId = 9999; - - $session = Tg_Session::fetch( $sessionId ); + $session = Tg_Session::fetch( self::TEST_SESSION_ID ); - $this->assertEquals($sessionId, $session->id ); + $this->assertEquals(self::TEST_SESSION_ID, $session->id ); $this->assertEquals( 'Wherein Grand Things Happen to our Heroes', $session->description ); $this->assertEquals( 'Lots of interesting things hapen to our heroes in this episode', $session->synopsis ); $this->assertEquals( new Zend_Date( '10-28-2008' ), $session->date ); } public function testFetchGetsGamingSessionByIdShouldHaveCampaign( ) { - $sessionId = 9999; $campaign = new Tg_Campaign( ); - $campaign->id = 9999; - $campaign->name = "Grand Campaign"; - $session = Tg_Session::fetch( $sessionId ); + $campaign->id = self::TEST_CAMPAIGN_ID; + $campaign->name = self::TEST_CAMPAIGN_NAME; + $session = Tg_Session::fetch( self::TEST_SESSION_ID ); $this->assertEquals( get_object_vars( $campaign ), get_object_vars( $session->campaign ) ); } public function testFetchGetsGamingSessionByIdShouldHaveMedia( ) { - $sessionId = 9999; $media = new Tg_Media( ); - $media->id = 9999; + $media->id = self::TEST_MEDIA_ID; $media->path = "12345.m4a"; $media->size = 3000000; $media->mimetype = 'audio/x-m4a'; $media->duration = '360000'; - $session = Tg_Session::fetch( $sessionId ); + $session = Tg_Session::fetch( self::TEST_SESSION_ID ); $this->assertEquals( get_object_vars( $media ), get_object_vars( $session->media ) ); } public function testFetchGetsGamingSessionByIdShouldHaveAuthor( ) { - $sessionId = 9999; $user = new Tg_User( ); - $user->id = 9999; + $user->id = self::TEST_AUTHOR_ID; $user->name = 'stm'; - $session = Tg_Session::fetch( $sessionId ); + $session = Tg_Session::fetch( self::TEST_SESSION_ID ); $this->assertEquals( get_object_vars( $user ), get_object_vars( $session->author ) ); } public function testFetchGetsGamingSessionByIdShouldHaveTags( ) { - - $sessionId = 9999; - $session = Tg_Session::fetch( $sessionId ); + $session = Tg_Session::fetch( self::TEST_SESSION_ID ); $this->assertContains( 'grand', $session->tags ); } public function testFetchAllShouldGetArrayOfSessions( ) { $sessions = Tg_Session::fetchAll( ); $this->assertContainsOnly( 'Tg_Session', $sessions ); } public function testFetchAllShouldGetTestSession( ) { - $sessionId = 9999; $sessions = Tg_Session::fetchAll( ); - $this->assertEquals( $sessionId, $sessions[0]->id ); + $this->assertEquals( self::TEST_SESSION_ID, $sessions[0]->id ); + } + + public function testFetchWithNullIdShouldReturnNewSession( ) { + $newSession = Tg_Session::fetch( ); + $this->assertType('Tg_Session', $newSession); + $this->assertNull($newSession->id); + } + + public function testGetFormShouldReturnZendFormObject( ) { + $session = Tg_Session::fetch( ); + $this->assertType('Zend_Form', $session->getForm()); + } + + public function testGetFormShouldReturnFormWithAllFields() { + $session = Tg_Session::fetch(); + $sessionForm = $session->getForm(); + $this->assertType('Zend_Form_Element', $sessionForm->id, 'ID field missing'); + $this->assertType('Zend_Form', $sessionForm->campaign, 'Campaign field missing'); + $this->assertType('Zend_Form_Element', $sessionForm->date,'Date field missing'); + $this->assertType('Zend_Form_Element', $sessionForm->description,'Description field missing'); + $this->assertType('Zend_Form_Element', $sessionForm->synopsis,'Synopsis field missing'); + //TODO add media test $this->assertType('Zend_Form_Element', $sessionForm->media,'Media field missing'); + $this->assertType('Zend_Form_Element', $sessionForm->tags,'Tags field missing'); + } + + public function testGetFormShouldBePopulated() { + $session = Tg_Session::fetch( self::TEST_SESSION_ID ); + $sessForm = $session->getForm(); + $this->assertEquals($session->id,$sessForm->id->getValue()); + $this->assertEquals($session->campaign->id,$sessForm->campaign->id->getValue()); + $this->assertEquals($session->date,new Zend_Date($sessForm->date->getValue())); + $this->assertEquals($session->description,$sessForm->description->getValue()); + $this->assertEquals($session->synopsis,$sessForm->synopsis->getValue()); + //TODO add media test $this->assertEquals($session->media->id,$sessForm->media->getValue()); + $this->assertEquals($session->tags,explode( ',', $sessForm->tags->getValue() )); + } + + public function testSaveNewSessionWithExistingSubObjectsShouldSave() { + $session = Tg_Session::fetch( ); + $session->campaign = Tg_Campaign::fetch( self::TEST_CAMPAIGN_ID ); + $session->media = Tg_Media::fetch( self::TEST_MEDIA_ID ); + $session->author = Tg_Media::fetch( self::TEST_AUTHOR_ID ); + $session->date = new Zend_Date(); + $session->description = "Test Description"; + $session->synopsis = "Test Synopsis"; + $session->tags = array('grand','newTag'); + + $session->save(); + + $fetchedSession = Tg_Session::fetch( $session->id ); + $this->assertEquals($session, $fetchedSession); } }
stm555/tablegeeks
91326ade4c33796ac6b7b329bbb1fd053d8ea709
removed base path define from class definition
diff --git a/scripts/bruteDbBuilder.php b/scripts/bruteDbBuilder.php index f137d99..2231c24 100644 --- a/scripts/bruteDbBuilder.php +++ b/scripts/bruteDbBuilder.php @@ -1,59 +1,58 @@ <?php -define( BASE_PATH, dirname( __FILE__ )); class bruteDbBuilder { const MYSQL_CLIENT = '~/bin/mysql'; const DB_HOST = 'localhost'; const DB_NAME = 'tablegeeks'; const ADMIN_UN = 'root'; const ADMIN_PW = 'smartone'; const TG_UN = 'tablegeeks'; const TG_PW = 'geeks@tables'; protected function buildCmd( $user, $pw, $file, $dbName = null ) { $cmd = self::MYSQL_CLIENT . ' -u ' . escapeshellarg( $user ) . ' -p' . escapeshellarg( $pw ); $cmd .= ( !is_null( $dbName ) ) ? ' ' . escapeshellarg( $dbName ) . ' ' : null; $cmd .= ' < '. escapeshellarg( $file); return $cmd; } private function execFile( $un, $pw, $file, $dbName = null) { $cmd = $this->buildCmd( $un, $pw, $file, $dbName ); exec( $cmd, $output, $exitCode ); if ( $exitCode !== 0 ) { throw new Exception ( 'Error executing file ' . $file . "\n" . implode( '\n', $output ) ); } } public function createDb( ) { - $this->execFile( self::ADMIN_UN, self::ADMIN_PW, BASE_PATH . '/schema/mysql/tablegeeks.schema.sql' ); + $this->execFile( self::ADMIN_UN, self::ADMIN_PW, dirname(__FILE__) . '/schema/mysql/tablegeeks.schema.sql' ); } public function createTables( ) { - $tableDefinitions = glob( realpath( BASE_PATH ) . '/schema/mysql/*.table.sql' ); + $tableDefinitions = glob( realpath( dirname(__FILE__) ) . '/schema/mysql/*.table.sql' ); foreach ( $tableDefinitions as $tableDef ) { $this->execFile( self::TG_UN, self::TG_PW, $tableDef, self::DB_NAME ); } $this->createForeignkeys( ); } private function createForeignkeys( ) { - $fkDefinitions = glob( realpath( BASE_PATH ) . '/schema/mysql/*.fk.sql' ); + $fkDefinitions = glob( realpath( dirname(__FILE__) ) . '/schema/mysql/*.fk.sql' ); foreach ( $fkDefinitions as $fkDef ) { $this->execFile( self::TG_UN, self::TG_PW, $fkDef, self::DB_NAME ); } } public function loadTestData( ) { - $this->execFile( self::TG_UN, self::TG_PW, BASE_PATH . '/data/mysql/testData.build.sql', self::DB_NAME ); + $this->execFile( self::TG_UN, self::TG_PW, dirname(__FILE__) . '/data/mysql/testData.build.sql', self::DB_NAME ); } }
stm555/tablegeeks
a3966ba9e85fd77d38d927b97fe6fc23b7f1d666
added the default db object to the registry
diff --git a/application/bootstrap.php b/application/bootstrap.php index 8eba870..6e03089 100644 --- a/application/bootstrap.php +++ b/application/bootstrap.php @@ -1,45 +1,46 @@ <?php // ** Check to see if the environment is already setup ** if (isset($bootstrap) && $bootstrap) { // Enable all errors so we'll know when something goes wrong. error_reporting(E_ALL | E_STRICT); ini_set('display_startup_errors', 1); ini_set('display_errors', 1); // Add our {{library}} directory to the include path so that PHP can find the Zend Framework classes. // you may wish to add other paths here, or keep system paths: set_include_path('../library' . PATH_SEPARATOR . get_include_path() set_include_path('../library' . PATH_SEPARATOR . realpath(dirname(__FILE__).'/../') . PATH_SEPARATOR . get_include_path()); // Set up autoload. // This is a nifty trick that allows ZF to load classes automatically so that you don't have to litter your // code with 'include' or 'require' statements. require_once "Zend/Loader.php"; Zend_Loader::registerAutoload(); } // ** Get the front controller ** // The Zend_Front_Controller class implements the Singleton pattern, which is a design pattern used to ensure // there is only one instance of Zend_Front_Controller created on each request. $frontController = Zend_Controller_Front::getInstance(); // Point the front controller to your action controller directory. $frontController->setControllerDirectory('../application/controllers'); // ** Load and register Basic Configuration File ** $config = new Zend_Config_Xml( dirname( __FILE__ ) . '/configs/tablegeeks.xml' ); Zend_Registry::set( 'config', $config ); // ** Initialize Logging $log = new Zend_Log( new Zend_Log_Writer_Firebug( ) ); Zend_Registry::set( 'log', $log ); // ** Load and register db access $profiler = new Zend_Db_Profiler_Firebug( 'All DB Queries' ); $db = Zend_Db::factory( $config->db->connection ); $profiler->setEnabled( $config->db->profiler->enabled ); $db->setProfiler( $profiler ); +Zend_Registry::set( 'db', $db ); Zend_Db_Table_Abstract::setDefaultAdapter( $db ); $frontController->throwExceptions(true);
stm555/tablegeeks
d1cd42f2667d4a17124e2c7126152061cd9a05dc
* more progress on the model
diff --git a/application/bootstrap.php b/application/bootstrap.php index 277a12e..8eba870 100644 --- a/application/bootstrap.php +++ b/application/bootstrap.php @@ -1,46 +1,45 @@ <?php // ** Check to see if the environment is already setup ** if (isset($bootstrap) && $bootstrap) { // Enable all errors so we'll know when something goes wrong. error_reporting(E_ALL | E_STRICT); ini_set('display_startup_errors', 1); ini_set('display_errors', 1); // Add our {{library}} directory to the include path so that PHP can find the Zend Framework classes. // you may wish to add other paths here, or keep system paths: set_include_path('../library' . PATH_SEPARATOR . get_include_path() set_include_path('../library' . PATH_SEPARATOR . realpath(dirname(__FILE__).'/../') . PATH_SEPARATOR . get_include_path()); // Set up autoload. // This is a nifty trick that allows ZF to load classes automatically so that you don't have to litter your // code with 'include' or 'require' statements. require_once "Zend/Loader.php"; Zend_Loader::registerAutoload(); } // ** Get the front controller ** // The Zend_Front_Controller class implements the Singleton pattern, which is a design pattern used to ensure // there is only one instance of Zend_Front_Controller created on each request. $frontController = Zend_Controller_Front::getInstance(); // Point the front controller to your action controller directory. $frontController->setControllerDirectory('../application/controllers'); // ** Load and register Basic Configuration File ** $config = new Zend_Config_Xml( dirname( __FILE__ ) . '/configs/tablegeeks.xml' ); Zend_Registry::set( 'config', $config ); // ** Initialize Logging $log = new Zend_Log( new Zend_Log_Writer_Firebug( ) ); Zend_Registry::set( 'log', $log ); // ** Load and register db access -//TODO make this detect backend and only set up when necessary $profiler = new Zend_Db_Profiler_Firebug( 'All DB Queries' ); $db = Zend_Db::factory( $config->db->connection ); $profiler->setEnabled( $config->db->profiler->enabled ); $db->setProfiler( $profiler ); Zend_Db_Table_Abstract::setDefaultAdapter( $db ); $frontController->throwExceptions(true); diff --git a/application/controllers/PodcastController.php b/application/controllers/PodcastController.php index 6bbe2a7..87724bb 100644 --- a/application/controllers/PodcastController.php +++ b/application/controllers/PodcastController.php @@ -1,46 +1,33 @@ <?php require_once 'application/models/Session.php'; /** * PodcastController * * @author stm */ class PodcastController extends Zend_Controller_Action { public function init() { /* Initialize action controller here */ } /** * indexAction * * @return void */ public function indexAction() { - //mock data - $session = new Tg_Session(); - $session->campaign = new Tg_Campaign(); - $session->campaign->name = "Grand Campaign!"; - $session->date = new Zend_Date( "10/14/2008" ); - $session->author = new Tg_User(); - $session->author->name = "stm"; - $session->description = "Wherein grand things happen to our heroes"; - $session->synopsis = "Lots of interesting things happen to our heroes in this episode!"; - $session->media = new Tg_Media( ); - $session->media->path = "/path/to/media.m4a"; - $session->media->size = 12345; - $session->media->mimetype = "audio/x-m4a"; - $session->media->duration = 34; - $session->addDate = new Zend_Date( "10/13/2008 3:00:00 PM CST" ); - $session->tags = array('fun','dragon','cthulu'); + $log = Zend_Registry::get( 'log' ); + $log->info( 'index action of Podcast controller' ); + $sessions = Tg_Session::fetchAll( ); //FIXME need to use a project defined base path here .. $viewHelpersPath = realpath(dirname(__FILE__) . '/../views/helpers'); $this->view->addHelperPath($viewHelpersPath,'Tg_View_Helper'); - $this->view->sessions = array($session,$session,$session); + $this->view->sessions = $sessions; $this->_helper->viewRenderer->setViewSuffix('pxml'); } } diff --git a/application/models/Session.php b/application/models/Session.php index 681c166..0f891fd 100644 --- a/application/models/Session.php +++ b/application/models/Session.php @@ -1,92 +1,155 @@ <?php require_once 'User.php'; require_once 'Campaign.php'; require_once 'Media.php'; /** * Tg_Session * * @author stm */ class Tg_Session { /** * unique session id * * @var integer */ public $id; /** * Campaign that this session part of * @var Tg_Campaign **/ public $campaign; /** * Stores date of the session * @var Zend_Date **/ public $date; /** * User who uploaded this session * @var Tg_User **/ public $author; /** * Description of this session * @var string **/ public $description = ''; /** * Synopsis of this session * @var string **/ public $synopsis = ''; /** * Media file for this session * @var Tg_Media **/ public $media; /** * Date that this session was added * @var Zend_Date **/ public $addDate; /** * Collection of tags related to this session * @var array **/ public $tags = array(); /** * Data access through table gateway pattern * * @var Zend_Db_Table_Abstract */ protected $_sessionTable; + /** + * Data access through table gateway pattern for tags + * + * @var Zend_Db_Table_Abstract + */ + protected $_tagTable; + private function _getSessionTable( ) { if ( is_null( $this->_sessionTable ) ) { require_once ( dirname( __FILE__ ) . '/Session/Db/MySql/SessionTable.php'); $this->_sessionTable = new Tg_Session_Db_MySql_SessionTable( ); } return $this->_sessionTable; } + private function _getTagTable( ) { + if ( is_null( $this->_tagTable ) ) + { + require_once ( dirname( __FILE__ ) . '/Tag/Db/MySql/TagTable.php'); + $this->_tagTable = new Tg_Tag_Db_MySql_TagTable( ); + } + return $this->_tagTable; + } + + private function _loadFromRow( Zend_Db_Table_Row $row ) + { + $this->id = $row->id; + $this->description = $row->description; + $this->synopsis = $row->synopsis; + $this->date = new Zend_Date( $row->date ); + $this->campaign = Tg_Campaign::fetch( $row->campaign ); + $this->author = Tg_User::fetch( $row->author ); + $this->media = Tg_Media::fetch( $row->media ); + $this->_populateTags( ); + } + + private function _populateTags( ) + { + $tagTable = $this->_getTagTable( ); + $select = $tagTable->select() + ->setIntegrityCheck(false) + ->from( $tagTable, 'tag' ) + ->joinInner( 'tags_xref', 'tags.id = tags_xref.tag', array( ) ) + ->where( "tags_xref.type = ?", Tg_Tag_Db_MySql_TagTable::TYPE_SESSION ) + ->where( "tags_xref.entity = ?", $this->id ); + Zend_Registry::get( 'log' )->debug( $select->assemble() ); + $this->tags = $tagTable->getAdapter( )->fetchCol( $select ); + } + //Static methods + /** + * fetch a gaming session by id + * + * @param integer $id + * @return Tg_Session + */ public static function fetch( $id ) { $session = new Tg_Session( ); $sessionTable = $session->_getSessionTable( ); $rowset = $sessionTable->find( $id ); - $row = $rowset->current( ); - $session->id = $row->id; - $session->description = $row->description; - $session->synopsis = $row->synopsis; - $session->date = new Zend_Date( $row->date ); + $session->_loadFromRow( $rowset->current( ) ); return $session; } + + /** + * Gets all gaming sessions and returns them in an array + * + * @return array + */ + public static function fetchAll( ) + { + $session = new Tg_Session( ); + $sessionTable = $session->_getSessionTable( ); + $rowset = $sessionTable->fetchAll( ); + $sessions = array( ); + foreach( $rowset as $row ) + { + $session = new Tg_Session( ); + $session->_loadFromRow( $row ); + $sessions[] = $session; + } + return $sessions; + } } diff --git a/application/models/Tag/Db/MySql/TagTable.php b/application/models/Tag/Db/MySql/TagTable.php new file mode 100644 index 0000000..c1f8cf2 --- /dev/null +++ b/application/models/Tag/Db/MySql/TagTable.php @@ -0,0 +1,11 @@ +<?php +require_once( dirname( __FILE__ ) . '/../../../../../library/Zend/Db/Table/Abstract.php' ); +class Tg_Tag_Db_MySql_TagTable extends Zend_Db_Table_Abstract +{ + const TYPE_SESSION = 'session'; + + protected $_name = 'tags'; + + protected $_primary = 'id'; +} + diff --git a/application/models/User.php b/application/models/User.php index f43b64d..4bec030 100644 --- a/application/models/User.php +++ b/application/models/User.php @@ -1,25 +1,54 @@ <?php /** * Tg_User * * @author stm */ class Tg_User { /** * unique user id * * @var integer */ public $id; /** * User's common name * * @var string */ public $name; -} + /** + * Data access through table gateway pattern + * + * @var Zend_Db_Table_Abstract + */ + protected $_userTable; + private function _getUserTable( ) + { + if ( is_null( $this->_userTable ) ) + { + require_once ( dirname( __FILE__ ) . '/User/Db/MySql/UserTable.php'); + $this->_userTable = new Tg_User_Db_MySql_UserTable( ); + } + return $this->_userTable; + } + + //Static methods + public static function fetch( $id ) + { + $user = new Tg_User( ); + $userTable = $user->_getUserTable( ); + $rowset = $userTable->find( $id ); + $row = $rowset->current( ); + $user->id = $row->id; + $user->name = $row->name; + + return $user; + } + +} diff --git a/application/models/User/Db/MySql/UserTable.php b/application/models/User/Db/MySql/UserTable.php new file mode 100644 index 0000000..92438d2 --- /dev/null +++ b/application/models/User/Db/MySql/UserTable.php @@ -0,0 +1,9 @@ +<?php +require_once( dirname( __FILE__ ) . '/../../../../../library/Zend/Db/Table/Abstract.php' ); +class Tg_User_Db_MySql_UserTable extends Zend_Db_Table_Abstract +{ + + protected $_name = 'users'; + + protected $_primary = 'id'; +} diff --git a/application/views/helpers/PodcastUrl.php b/application/views/helpers/PodcastUrl.php index 8c44633..848364b 100644 --- a/application/views/helpers/PodcastUrl.php +++ b/application/views/helpers/PodcastUrl.php @@ -1,15 +1,17 @@ <?php class Tg_View_Helper_PodcastUrl extends Zend_View_Helper_Abstract { /** * Takes a local path to a podcast file and converts it into a valid url + * + * @TODO user of the SERVER_NAME super global is probably a security hole -- switch to configuration value * * @param string $filePath Path to podcast audio file * @return string * @author stm **/ public function podcastUrl($filePath) { - return "http://tablegeeks.com/audio/12345.m4a"; + return "http://{$_SERVER['SERVER_NAME']}/audio/12345.m4a"; } } diff --git a/public/audio/12345.m4a b/public/audio/12345.m4a new file mode 100644 index 0000000..1955cba Binary files /dev/null and b/public/audio/12345.m4a differ diff --git a/tests/controllers/podcastControllerTest.php b/tests/controllers/podcastControllerTest.php index 5148a85..951494a 100644 --- a/tests/controllers/podcastControllerTest.php +++ b/tests/controllers/podcastControllerTest.php @@ -1,21 +1,20 @@ <?php -//ini_set( 'include_path', '../../library' . DIRECTORY_SEPARATOR . ini_get( 'include_path' )); -//require_once 'Zend/Test/PHPUnit/ControllerTestCase.php'; +require dirname( __FILE__ ) . '/../TestHelper.php'; $bootstrap = true; -require '../../application/bootstrap.php'; +require dirname( __FILE__ ) . '/../../application/bootstrap.php'; class podcastControlerTest extends Zend_Test_PHPUnit_ControllerTestCase { public function setUp( ) { - $this->bootstrap = '../../application/bootstrap.php'; + $this->bootstrap = dirname( __FILE__ ) . '/../../application/bootstrap.php'; parent::setUp( ); } public function testMainFeed( ) { $this->dispatch( '/' ); $this->assertXpath( 'rss' ); $this->assertXpath( 'rss/channel' ); $this->assertXpath( 'rss/channel/title' ); } } diff --git a/tests/models/SessionTest.php b/tests/models/SessionTest.php index d557d9d..44f75b3 100644 --- a/tests/models/SessionTest.php +++ b/tests/models/SessionTest.php @@ -1,57 +1,97 @@ <?php require_once( dirname( __FILE__ ) . '/../TestHelper.php' ); require_once( 'PHPUnit/Framework.php' ); require_once( 'Session.php' ); require_once( Zend_Registry::get( 'testBootstrap' ) ); +/** + * SessionTest + * @TODO refactor all these hard coded test values to defines or something + * @TODO need to add support for tags + * @author stm + */ class SessionTest extends PHPUnit_Framework_TestCase { private $dbUser = 'tablegeeks'; private $dbPw = 'geeks@tables'; private $dbName = 'tablegeeks'; public function setUp( ) { //load database with test data exec( "mysql5 -u {$this->dbUser} -p {$this->dbPw} {$this->dbName} < " . Zend_Registry::get( 'testRoot' ) . "/scripts/data/mysql/testData.build.sql" ); } public function tearDown( ) { //empty out all tables exec( "mysql5 -u {$this->dbUser} -p {$this->dbPw} {$this->dbName} < " . Zend_Registry::get( 'testRoot' ) . "/scripts/data/mysql/testData.destroy.sql" ); } public function testFetchGetsAGamingSession( ) { $session = Tg_Session::fetch( 1 ); $this->assertType( 'Tg_Session', $session ); } - public function testFetchGetsGamingSessionById( ) { + public function testFetchGetsGamingSessionByIdShouldHavePrimitiveValues( ) { + $sessionId = 1; + + $session = Tg_Session::fetch( $sessionId ); + + $this->assertEquals($sessionId, $session->id ); + $this->assertEquals( 'Wherein Grand Things Happen to our Heroes', $session->description ); + $this->assertEquals( 'Lots of interesting things hapen to our heroes in this episode', $session->synopsis ); + $this->assertEquals( new Zend_Date( '10-28-2008' ), $session->date ); + } + + public function testFetchGetsGamingSessionByIdShouldHaveCampaign( ) { $sessionId = 1; $campaign = new Tg_Campaign( ); $campaign->id = 1; - $campgain->name = "Grand Campaign"; + $campaign->name = "Grand Campaign"; + $session = Tg_Session::fetch( $sessionId ); + $this->assertEquals( get_object_vars( $campaign ), get_object_vars( $session->campaign ) ); + } + + public function testFetchGetsGamingSessionByIdShouldHaveMedia( ) { + $sessionId = 1; $media = new Tg_Media( ); $media->id = 1; $media->path = "12345.m4a"; $media->size = 3000000; $media->mimetype = 'audio/x-m4a'; $media->duration = '360000'; - $user = new Tg_Users( ); + $session = Tg_Session::fetch( $sessionId ); + $this->assertEquals( get_object_vars( $media ), get_object_vars( $session->media ) ); + } + + public function testFetchGetsGamingSessionByIdShouldHaveAuthor( ) { + $sessionId = 1; + $user = new Tg_User( ); $user->id = 1; - $user->name = stm; + $user->name = 'stm'; + $session = Tg_Session::fetch( $sessionId ); + $this->assertEquals( get_object_vars( $user ), get_object_vars( $session->author ) ); + } + public function testFetchGetsGamingSessionByIdShouldHaveTags( ) { + + $sessionId = 1; $session = Tg_Session::fetch( $sessionId ); + $this->assertContains( 'grand', $session->tags ); + } + + public function testFetchAllShouldGetArrayOfSessions( ) { + $sessions = Tg_Session::fetchAll( ); - $this->assertEquals($sessionId, $session->id ); - $this->assertEquals( 'Wherein Grand Things Happen to our Heroes', $session->description ); - $this->assertEquals( 'Lots of interesting things hapen to our heroes in this episode', $session->synopsis ); - $this->assertEquals( new Zend_Date( '10-28-2008' ), $session->date ); - $this->assertEquals( $campaign, $session->campaign ); - $this->assertEquals( $media, $session->media ); - $this->assertEquals( $user, $session->user ); + $this->assertContainsOnly( 'Tg_Session', $sessions ); + } + + public function testFetchAllShouldGetTestSession( ) { + $sessionId = 1; + $sessions = Tg_Session::fetchAll( ); + $this->assertEquals( $sessionId, $sessions[0]->id ); } } diff --git a/tests/models/UserTest.php b/tests/models/UserTest.php new file mode 100644 index 0000000..941d16c --- /dev/null +++ b/tests/models/UserTest.php @@ -0,0 +1,41 @@ +<?php +require_once( dirname( __FILE__ ) . '/../TestHelper.php' ); +require_once( 'PHPUnit/Framework.php' ); +require_once( 'User.php' ); +require_once( Zend_Registry::get( 'testBootstrap' ) ); + +class UserTest extends PHPUnit_Framework_TestCase +{ + private $dbUser = 'tablegeeks'; + private $dbPw = 'geeks@tables'; + private $dbName = 'tablegeeks'; + + public function setUp( ) + { + //load database with test data + exec( "mysql5 -u {$this->dbUser} -p {$this->dbPw} {$this->dbName} < " . Zend_Registry::get( 'testRoot' ) . "/scripts/data/mysql/testData.build.sql" ); + } + public function tearDown( ) + { + //empty out all tables + exec( "mysql5 -u {$this->dbUser} -p {$this->dbPw} {$this->dbName} < " . Zend_Registry::get( 'testRoot' ) . "/scripts/data/mysql/testData.destroy.sql" ); + } + + public function testFetchGetsAUser( ) + { + $user = Tg_User::fetch( 1 ); + + $this->assertType( 'Tg_User', $user ); + + } + + public function testFetchGetsUserById( ) { + $userId = 1; + $userName = 'stm'; + + $user = Tg_User::fetch( $userId ); + + $this->assertEquals($userId, $user->id ); + $this->assertEquals( $userName, $user->name ); + } +}
stm555/tablegeeks
e2ef90aaa03e3bfbb1a5f5579c162d5b58b14ce1
* Added a script to load the database (w/ unit tests)
diff --git a/scripts/bruteDbBuilder.php b/scripts/bruteDbBuilder.php new file mode 100644 index 0000000..f137d99 --- /dev/null +++ b/scripts/bruteDbBuilder.php @@ -0,0 +1,59 @@ +<?php +define( BASE_PATH, dirname( __FILE__ )); +class bruteDbBuilder { + + const MYSQL_CLIENT = '~/bin/mysql'; + const DB_HOST = 'localhost'; + const DB_NAME = 'tablegeeks'; + const ADMIN_UN = 'root'; + const ADMIN_PW = 'smartone'; + const TG_UN = 'tablegeeks'; + const TG_PW = 'geeks@tables'; + + protected function buildCmd( $user, $pw, $file, $dbName = null ) + { + $cmd = self::MYSQL_CLIENT + . ' -u ' . escapeshellarg( $user ) + . ' -p' . escapeshellarg( $pw ); + $cmd .= ( !is_null( $dbName ) ) ? ' ' . escapeshellarg( $dbName ) . ' ' : null; + $cmd .= ' < '. escapeshellarg( $file); + return $cmd; + } + + private function execFile( $un, $pw, $file, $dbName = null) + { + $cmd = $this->buildCmd( $un, $pw, $file, $dbName ); + exec( $cmd, $output, $exitCode ); + if ( $exitCode !== 0 ) + { + throw new Exception ( 'Error executing file ' . $file . "\n" . implode( '\n', $output ) ); + } + } + + public function createDb( ) { + $this->execFile( self::ADMIN_UN, self::ADMIN_PW, BASE_PATH . '/schema/mysql/tablegeeks.schema.sql' ); + } + + public function createTables( ) { + $tableDefinitions = glob( realpath( BASE_PATH ) . '/schema/mysql/*.table.sql' ); + foreach ( $tableDefinitions as $tableDef ) + { + $this->execFile( self::TG_UN, self::TG_PW, $tableDef, self::DB_NAME ); + } + $this->createForeignkeys( ); + } + + private function createForeignkeys( ) { + $fkDefinitions = glob( realpath( BASE_PATH ) . '/schema/mysql/*.fk.sql' ); + foreach ( $fkDefinitions as $fkDef ) + { + $this->execFile( self::TG_UN, self::TG_PW, $fkDef, self::DB_NAME ); + } + + } + + public function loadTestData( ) { + $this->execFile( self::TG_UN, self::TG_PW, BASE_PATH . '/data/mysql/testData.build.sql', self::DB_NAME ); + } +} + diff --git a/scripts/buildDbWithTest.php b/scripts/buildDbWithTest.php new file mode 100644 index 0000000..edbd8fa --- /dev/null +++ b/scripts/buildDbWithTest.php @@ -0,0 +1,10 @@ +<?php +require_once ( 'bruteDbBuilder.php' ); + +$builder = new bruteDbBuilder( ); +//create database +$builder->createDb( ); +//create tables +$builder->createTables( ); +//load test data +$builder->loadTestData( ); diff --git a/scripts/data/mysql/testData.build.sql b/scripts/data/mysql/testData.build.sql index 2127e51..acf18c7 100644 --- a/scripts/data/mysql/testData.build.sql +++ b/scripts/data/mysql/testData.build.sql @@ -1,4 +1,6 @@ -INSERT INTO campaigns ( `id`, `name`, `created` ) VALUES ( '1', 'Grand Campaign', now( ) ); -INSERT INTO media ( `id`, `path`, `size`, `mimetype`, `duration`, `created` ) VALUES ( '1', '12345.m4a', '3000000', 'audio/x-m4a', '360000', now( ) ); -INSERT INTO users ( `id`, `name`, `created` ) VALUES ( '1', 'stm', now( ) ); -INSERT INTO sessions ( `id`, `description`, `synopsis`, `date`, `campaign`, `author`, `media`, `created` ) VALUES ( '1', 'Wherein Grand Things Happen to our Heroes', 'Lots of interesting things hapen to our heroes in this episode', '2008-10-28', '1', '1', '1', now( ) ); +INSERT INTO campaigns ( `id`, `name`, `created` ) VALUES ( '9999', 'Grand Campaign', now( ) ); +INSERT INTO media ( `id`, `path`, `size`, `mimetype`, `duration`, `created` ) VALUES ( '9999', '12345.m4a', '3000000', 'audio/x-m4a', '360000', now( ) ); +INSERT INTO users ( `id`, `name`, `created` ) VALUES ( '9999', 'stm', now( ) ); +INSERT INTO sessions ( `id`, `description`, `synopsis`, `date`, `campaign`, `author`, `media`, `created` ) VALUES ( '9999', 'Wherein Grand Things Happen to our Heroes', 'Lots of interesting things hapen to our heroes in this episode', '2008-10-28', '9999', '9999', '9999', now( ) ); +INSERT INTO tags (`id`, `tag`, `created`) VALUES ('9999', 'grand', now()); +INSERT INTO tags_xref (`tag`, `type`, `entity`, `created`) VALUES ('9999', 'session', '9999', now()); diff --git a/scripts/schema/mysql/media.table.sql b/scripts/schema/mysql/media.table.sql index 3982a28..5fa21fc 100644 --- a/scripts/schema/mysql/media.table.sql +++ b/scripts/schema/mysql/media.table.sql @@ -1,12 +1,12 @@ CREATE TABLE `tablegeeks`.`media` ( - `id` INT UNSIGNED NOT NULL, + `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `path` VARCHAR(512) NOT NULL, `size` INT UNSIGNED DEFAULT NULL, `mimetype` VARCHAR(50) DEFAULT NULL COMMENT 'Mimetype of media file', `duration` INT UNSIGNED DEFAULT NULL COMMENT 'duration in seconds of media', `created` DATETIME NOT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB CHARACTER SET utf8 COMMENT = 'media files'; diff --git a/scripts/schema/mysql/tags_xref.table.sql b/scripts/schema/mysql/tags_xref.table.sql index f588620..f41ffcb 100644 --- a/scripts/schema/mysql/tags_xref.table.sql +++ b/scripts/schema/mysql/tags_xref.table.sql @@ -1,10 +1,10 @@ CREATE TABLE `tablegeeks`.`tags_xref` ( `tag` INT UNSIGNED NOT NULL COMMENT 'fk to tags', - `type` INT UNSIGNED NOT NULL COMMENT 'type of entity that is tagged', + `type` ENUM('session','user','campaign') NOT NULL COMMENT 'type of entity that is tagged', `entity` INT UNSIGNED NOT NULL COMMENT 'fk to thing that is tagged', `created` DATETIME NOT NULL COMMENT 'std. field', PRIMARY KEY (`tag`, `type`, `entity`) ) ENGINE = InnoDB CHARACTER SET utf8 COMMENT = 'ties tags to things'; diff --git a/tests/TestHelper.php b/tests/TestHelper.php index 8b72b4b..0c8cb18 100644 --- a/tests/TestHelper.php +++ b/tests/TestHelper.php @@ -1,71 +1,66 @@ <?php /* * Start output buffering */ ob_start(); /* * Set error reporting to the level to which Zend Framework code must comply. */ error_reporting( E_ALL | E_STRICT ); /* * Maximize memory limit */ ini_set('memory_limit', -1); -/* - * Set default timezone - */ -date_default_timezone_set('US/CENTRAL'); - /* * Determine the root, library, tests, and models directories */ $root = realpath(dirname(__FILE__) . '/../'); $library = $root . '/library'; $tests = $root . '/tests'; $models = $root . '/application/models'; $controllers = $root . '/application/controllers'; /* * Prepend the library/, tests/, and models/ directories to the * include_path. This allows the tests to run out of the box. */ $path = array( $models, $library, $tests, get_include_path() ); set_include_path(implode(PATH_SEPARATOR, $path)); /** * Register autoloader */ require_once 'Zend/Loader.php'; Zend_Loader::registerAutoload(); /* * Add library/ and models/ directory to the PHPUnit code coverage * whitelist. This has the effect that only production code source files appear * in the code coverage report and that all production code source files, even * those that are not covered by a test yet, are processed. */ if (defined('TESTS_GENERATE_REPORT') && TESTS_GENERATE_REPORT === true && version_compare(PHPUnit_Runner_Version::id(), '3.1.6', '>=')) { PHPUnit_Util_Filter::addDirectoryToWhitelist($library); PHPUnit_Util_Filter::addDirectoryToWhitelist($models); PHPUnit_Util_Filter::addDirectoryToWhitelist($controllers); } /** * Store application root in registry */ Zend_Registry::set('testRoot', $root); Zend_Registry::set('testBootstrap', $root . '/application/bootstrap.php'); /* * Unset global variables that are no longer needed. */ unset($root, $library, $models, $controllers, $tests, $path); diff --git a/tests/scripts/bruteDbBuilderTest.php b/tests/scripts/bruteDbBuilderTest.php new file mode 100644 index 0000000..0aea807 --- /dev/null +++ b/tests/scripts/bruteDbBuilderTest.php @@ -0,0 +1,79 @@ +<?php +require_once( 'PHPUnit/Framework.php' ); +require_once( dirname( __FILE__ ) . '/../../scripts/bruteDbBuilder.php' ); +require_once( dirname( __FILE__ ) . '/../TestHelper.php' ); + +/** + * bruteDbBuilderTest + * @author stm + */ +class bruteDbBuilderTest extends PHPUnit_Framework_TestCase +{ + private $connInfo = array( 'host' => bruteDbBuilder::DB_HOST, + 'username' => bruteDbBuilder::TG_UN, + 'password' => bruteDbBuilder::TG_PW, + 'dbname' => bruteDbBuilder::DB_NAME); + private $dbAdapter; + + public function setUp( ) + { + $this->dbAdapter = Zend_Db::factory( 'Pdo_Mysql', $this->connInfo ); + } + public function tearDown( ) + { + $tearDownConnInfo = $this->connInfo; + $tearDownConnInfo['username'] = bruteDbBuilder::ADMIN_UN; + $tearDownConnInfo['password'] = bruteDbBuilder::ADMIN_PW; + + $tearDownAdapter = Zend_Db::factory( 'Pdo_Mysql', $tearDownConnInfo ); + $tearDownAdapter->query( 'DROP DATABASE `tablegeeks`' ); + } + + public function testCreateDb( ) + { + $builder = new bruteDbBuilder( ); + $builder->createDb( ); + + $databases = $this->dbAdapter->fetchCol( 'SHOW DATABASES;' ); + + $this->assertContains( 'tablegeeks', $databases ); + + } + + public function testCreateTables( ) + { + $builder = new bruteDbBuilder( ); + $builder->createDb( ); + $builder->createTables( ); + + $tables = $this->dbAdapter->fetchCol( 'SHOW TABLES' ); + + //TODO test for foreign keys as well + $this->assertContains( 'sessions', $tables ); + $this->assertContains( 'campaigns', $tables ); + $this->assertContains( 'media', $tables ); + $this->assertContains( 'users', $tables ); + $this->assertContains( 'tags', $tables ); + $this->assertContains( 'tags_xref', $tables ); + } + + public function testLoadTestData( ) { + $builder = new bruteDbBuilder( ); + $builder->createDb( ); + $builder->createTables( ); + $builder->loadTestData( ); + + $count = $this->dbAdapter->fetchOne( 'SELECT count( 1 ) as count FROM campaigns WHERE id=?;',9999 ); + $this->assertEquals( 1, $count ); + $count = $this->dbAdapter->fetchOne( 'SELECT count( 1 ) as count FROM media WHERE id=?;',9999 ); + $this->assertEquals( 1, $count ); + $count = $this->dbAdapter->fetchOne( 'SELECT count( 1 ) as count FROM sessions WHERE id=?;',9999 ); + $this->assertEquals( 1, $count ); + $count = $this->dbAdapter->fetchOne( 'SELECT count( 1 ) as count FROM users WHERE id=?;',9999 ); + $this->assertEquals( 1, $count ); + $count = $this->dbAdapter->fetchOne( 'SELECT count( 1 ) as count FROM tags WHERE id=?;',9999 ); + $this->assertEquals( 1, $count ); + $count = $this->dbAdapter->fetchOne( 'SELECT count( 1 ) as count FROM tags_xref WHERE tag=? AND type=? AND entity=?;',array( 9999,'session',9999) ); + $this->assertEquals( 1, $count ); + } +}
stm555/tablegeeks
b94257f338eac783436d411f4f3d7ec1573b5f06
* Progress on loading session (w/ complete unit tests)
diff --git a/application/models/Campaign.php b/application/models/Campaign.php index e3f4f0e..b8df78e 100644 --- a/application/models/Campaign.php +++ b/application/models/Campaign.php @@ -1,12 +1,48 @@ <?php - class Tg_Campaign { + /** + * unique campaign id + * + * @var integer + */ + public $id; + /** * Campaign Name * * @var string */ public $name = ''; + + /** + * Data access through table gateway pattern + * + * @var Zend_Db_Table_Abstract + */ + protected $_campaignTable; + + private function _getCampaignTable( ) + { + if ( is_null( $this->_campaignTable ) ) + { + require_once ( dirname( __FILE__ ) . '/Campaign/Db/MySql/CampaignTable.php'); + $this->_campaignTable = new Tg_Campaign_Db_MySql_CampaignTable( ); + } + return $this->_campaignTable; + } + + //Static methods + public static function fetch( $id ) + { + $campaign = new Tg_Campaign( ); + $campaignTable = $campaign->_getCampaignTable( ); + $rowset = $campaignTable->find( $id ); + $row = $rowset->current( ); + $campaign->id = $row->id; + $campaign->name = $row->name; + + return $campaign; + } } diff --git a/application/models/Campaign/Db/MySql/CampaignTable.php b/application/models/Campaign/Db/MySql/CampaignTable.php new file mode 100644 index 0000000..0f9316e --- /dev/null +++ b/application/models/Campaign/Db/MySql/CampaignTable.php @@ -0,0 +1,9 @@ +<?php +require_once( dirname( __FILE__ ) . '/../../../../../library/Zend/Db/Table/Abstract.php' ); +class Tg_Campaign_Db_MySql_CampaignTable extends Zend_Db_Table_Abstract +{ + + protected $_name = 'campaigns'; + + protected $_primary = 'id'; +} diff --git a/application/models/Media.php b/application/models/Media.php index 33cd14e..569dc9d 100644 --- a/application/models/Media.php +++ b/application/models/Media.php @@ -1,63 +1,102 @@ <?php /** * Tg_Media * * @author stm */ class Tg_Media { const DURATION_TYPE_SECONDS = 0; const DURATION_TYPE_MINUTES = 1; const DURATION_TYPE_HOURS = 2; + /** + * unique media id + * + * @var integer + */ + public $id; + /** * local relative path to media file * * @var string */ public $path =''; /** * size of media file * * @var int */ public $size = 0; /** * mimetype of media file * * @var string */ public $mimetype = ''; /** * duration in seconds of media * * @var int */ public $duration = 0; + /** + * Data access through table gateway pattern + * + * @var Zend_Db_Table_Abstract + */ + protected $_mediaTable; + + private function _getMediaTable( ) + { + if ( is_null( $this->_mediaTable ) ) + { + require_once ( dirname( __FILE__ ) . '/Media/Db/MySql/MediaTable.php'); + $this->_mediaTable = new Tg_Media_Db_MySql_MediaTable( ); + } + return $this->_mediaTable; + } + + //Static methods + public static function fetch( $id ) + { + $media = new Tg_Media( ); + $mediaTable = $media->_getMediaTable( ); + $rowset = $mediaTable->find( $id ); + $row = $rowset->current( ); + $media->id = $row->id; + $media->path = $row->path; + $media->size = $row->size; + $media->mimetype = $row->mimetype; + $media->duration = $row->duration; + + return $media; + } /** * getDuration returns a string formatted duration based on the unit * * @param int $unit * @return string */ public function getDuration( $unit = self::DURATION_TYPE_SECONDS ) { switch ( $unit ) { case self::DURATION_TYPE_SECONDS: //seconds return (string)$this->duration; case self::DURATION_TYPE_MINUTES: //minutes //seconds return floor( $this->duration / 60 ) . ':' . $this->duration % 60; case self::DURATION_TYPE_HOURS: //hours //minutes //seconds return floor ( $this->duration / ( 60*60 ) ) . ':' . floor( $this->duration / 60 ) % 60 . ':' . $this->duration % 60; default: throw new Exception( 'Invalid duration unit' ); } } } diff --git a/application/models/Media/Db/MySql/MediaTable.php b/application/models/Media/Db/MySql/MediaTable.php new file mode 100644 index 0000000..459a80b --- /dev/null +++ b/application/models/Media/Db/MySql/MediaTable.php @@ -0,0 +1,9 @@ +<?php +require_once( dirname( __FILE__ ) . '/../../../../../library/Zend/Db/Table/Abstract.php' ); +class Tg_Media_Db_MySql_MediaTable extends Zend_Db_Table_Abstract +{ + + protected $_name = 'media'; + + protected $_primary = 'id'; +} diff --git a/application/models/Session.php b/application/models/Session.php index 54f3d93..681c166 100644 --- a/application/models/Session.php +++ b/application/models/Session.php @@ -1,85 +1,92 @@ <?php -require_once dirname( __FILE__ ) . '/../../library/Stm/MultiStorageModel/Abstract.php'; require_once 'User.php'; require_once 'Campaign.php'; require_once 'Media.php'; /** * Tg_Session * * @author stm */ -class Tg_Session extends Stm_MultiStorageModel_Abstract +class Tg_Session { + /** + * unique session id + * + * @var integer + */ + public $id; + /** * Campaign that this session part of * @var Tg_Campaign **/ public $campaign; /** * Stores date of the session * @var Zend_Date **/ public $date; /** * User who uploaded this session * @var Tg_User **/ public $author; /** * Description of this session * @var string **/ public $description = ''; /** * Synopsis of this session * @var string **/ public $synopsis = ''; /** * Media file for this session * @var Tg_Media **/ public $media; /** * Date that this session was added * @var Zend_Date **/ public $addDate; /** * Collection of tags related to this session * @var array **/ public $tags = array(); /** * Data access through table gateway pattern * * @var Zend_Db_Table_Abstract */ - protected $_table; + protected $_sessionTable; - public function getStorageAdapter( ) + private function _getSessionTable( ) { - switch ( $this->_storageType ) + if ( is_null( $this->_sessionTable ) ) { - case self::STORAGE_DB: - return $this->_getTable( ); - case null: - throw new Exception ( 'Storage Type Not Set' ); - default: - throw new Exception ( 'Unsupported Storage Type Set' ); + require_once ( dirname( __FILE__ ) . '/Session/Db/MySql/SessionTable.php'); + $this->_sessionTable = new Tg_Session_Db_MySql_SessionTable( ); } + return $this->_sessionTable; } - private function _getTable( ) + //Static methods + public static function fetch( $id ) { - if ( is_null( $this->_table ) ) - { - require_once ( dirname( __FILE__ ) . '/Session/Db/MySql/Table.php'); - $this->_table = new Tg_Session_Db_MySql_Table( ); - } - return $this->_table; - } + $session = new Tg_Session( ); + $sessionTable = $session->_getSessionTable( ); + $rowset = $sessionTable->find( $id ); + $row = $rowset->current( ); + $session->id = $row->id; + $session->description = $row->description; + $session->synopsis = $row->synopsis; + $session->date = new Zend_Date( $row->date ); + return $session; + } } diff --git a/application/models/Session/Db/MySql/Table.php b/application/models/Session/Db/MySql/SessionTable.php similarity index 70% rename from application/models/Session/Db/MySql/Table.php rename to application/models/Session/Db/MySql/SessionTable.php index 45b0770..aafbb93 100644 --- a/application/models/Session/Db/MySql/Table.php +++ b/application/models/Session/Db/MySql/SessionTable.php @@ -1,9 +1,9 @@ <?php require_once( dirname( __FILE__ ) . '/../../../../../library/Zend/Db/Table/Abstract.php' ); -class Tg_Session_Db_MySql_Table extends Zend_Db_Table_Abstract +class Tg_Session_Db_MySql_SessionTable extends Zend_Db_Table_Abstract { protected $_name = 'sessions'; protected $_primary = 'id'; } diff --git a/application/models/User.php b/application/models/User.php index 3153ff7..f43b64d 100644 --- a/application/models/User.php +++ b/application/models/User.php @@ -1,18 +1,25 @@ <?php /** * Tg_User * * @author stm */ class Tg_User { + /** + * unique user id + * + * @var integer + */ + public $id; + /** * User's common name * * @var string */ public $name; } diff --git a/scripts/data/mysql/testData.build.sql b/scripts/data/mysql/testData.build.sql new file mode 100644 index 0000000..2127e51 --- /dev/null +++ b/scripts/data/mysql/testData.build.sql @@ -0,0 +1,4 @@ +INSERT INTO campaigns ( `id`, `name`, `created` ) VALUES ( '1', 'Grand Campaign', now( ) ); +INSERT INTO media ( `id`, `path`, `size`, `mimetype`, `duration`, `created` ) VALUES ( '1', '12345.m4a', '3000000', 'audio/x-m4a', '360000', now( ) ); +INSERT INTO users ( `id`, `name`, `created` ) VALUES ( '1', 'stm', now( ) ); +INSERT INTO sessions ( `id`, `description`, `synopsis`, `date`, `campaign`, `author`, `media`, `created` ) VALUES ( '1', 'Wherein Grand Things Happen to our Heroes', 'Lots of interesting things hapen to our heroes in this episode', '2008-10-28', '1', '1', '1', now( ) ); diff --git a/scripts/data/mysql/testData.destroy.sql b/scripts/data/mysql/testData.destroy.sql new file mode 100644 index 0000000..0f72c06 --- /dev/null +++ b/scripts/data/mysql/testData.destroy.sql @@ -0,0 +1,4 @@ +TRUNCATE TABLE sessions; +TRUNCATE TABLE users; +TRUNCATE TABLE media; +TRUNCATE TABLE campaigns; diff --git a/tests/TestHelper.php b/tests/TestHelper.php new file mode 100644 index 0000000..8b72b4b --- /dev/null +++ b/tests/TestHelper.php @@ -0,0 +1,71 @@ +<?php +/* + * Start output buffering + */ +ob_start(); + +/* + * Set error reporting to the level to which Zend Framework code must comply. + */ +error_reporting( E_ALL | E_STRICT ); + +/* + * Maximize memory limit + */ +ini_set('memory_limit', -1); + +/* + * Set default timezone + */ +date_default_timezone_set('US/CENTRAL'); + +/* + * Determine the root, library, tests, and models directories + */ +$root = realpath(dirname(__FILE__) . '/../'); +$library = $root . '/library'; +$tests = $root . '/tests'; +$models = $root . '/application/models'; +$controllers = $root . '/application/controllers'; + +/* + * Prepend the library/, tests/, and models/ directories to the + * include_path. This allows the tests to run out of the box. + */ +$path = array( + $models, + $library, + $tests, + get_include_path() +); +set_include_path(implode(PATH_SEPARATOR, $path)); + +/** + * Register autoloader + */ +require_once 'Zend/Loader.php'; +Zend_Loader::registerAutoload(); + +/* + * Add library/ and models/ directory to the PHPUnit code coverage + * whitelist. This has the effect that only production code source files appear + * in the code coverage report and that all production code source files, even + * those that are not covered by a test yet, are processed. + */ +if (defined('TESTS_GENERATE_REPORT') && TESTS_GENERATE_REPORT === true && + version_compare(PHPUnit_Runner_Version::id(), '3.1.6', '>=')) { + PHPUnit_Util_Filter::addDirectoryToWhitelist($library); + PHPUnit_Util_Filter::addDirectoryToWhitelist($models); + PHPUnit_Util_Filter::addDirectoryToWhitelist($controllers); +} + +/** + * Store application root in registry + */ +Zend_Registry::set('testRoot', $root); +Zend_Registry::set('testBootstrap', $root . '/application/bootstrap.php'); + +/* + * Unset global variables that are no longer needed. + */ +unset($root, $library, $models, $controllers, $tests, $path); diff --git a/tests/library/Stm/MultiStorageModel/AbstractTest.php b/tests/library/Stm/MultiStorageModel/AbstractTest.php deleted file mode 100644 index fa561d6..0000000 --- a/tests/library/Stm/MultiStorageModel/AbstractTest.php +++ /dev/null @@ -1,59 +0,0 @@ -<?php -require_once( 'PHPUnit/Framework.php' ); -require_once( dirname( __FILE__ ) . '/../../../../library/Stm/MultiStorageModel/Abstract.php' ); -require_once( dirname( __FILE__ ) . '/../../../../library/Zend/Db/Table/Abstract.php' ); - -class Stm_MultiStorageModel_AbstractTest extends PHPUnit_Framework_TestCase -{ - /** - * testSetStorage - * tests that setting the storage to Db causes a Zend_Db_Table adapter to be used - * as implemented in demo model class at bottom of file - * - */ - public function testSetStorageDb( ) - { - Stm_MultiStorageModel_Abstract::setStorage( Stm_MultiStorageModel_Abstract::STORAGE_DB ); - - $model = new DemoModel( ); - - $this->assertType( 'Zend_Db_Table_Abstract', $model->getStorageAdapter( ) ); - - } -} - -class DemoModel extends Stm_MultiStorageModel_Abstract -{ - private $_table = null; - - public function getStorageAdapter( ) - { - switch ( $this->_storageType ) - { - case self::STORAGE_DB: - return $this->_getTable( ); - case null: - throw new Exception ( 'Storage Type Not Set' ); - default: - throw new Exception ( 'Unsupported Storage Type Set' ); - } - } - private function _getTable( ) - { - if ( is_null( $this->_table ) ) - { - $this->_table = new DemoTable( ); - } - return $this->_table; - } - -} -class DemoTable extends Zend_Db_Table_Abstract -{ - public function __construct( ) - { - //overloading so it doesn't require an adapter or anything - - } - -} diff --git a/tests/models/CampaignTest.php b/tests/models/CampaignTest.php new file mode 100644 index 0000000..3842334 --- /dev/null +++ b/tests/models/CampaignTest.php @@ -0,0 +1,41 @@ +<?php +require_once( dirname( __FILE__ ) . '/../TestHelper.php' ); +require_once( 'PHPUnit/Framework.php' ); +require_once( 'Campaign.php' ); +require_once( Zend_Registry::get( 'testBootstrap' ) ); + +class CampaignTest extends PHPUnit_Framework_TestCase +{ + private $dbUser = 'tablegeeks'; + private $dbPw = 'geeks@tables'; + private $dbName = 'tablegeeks'; + + public function setUp( ) + { + //load database with test data + exec( "mysql5 -u {$this->dbUser} -p {$this->dbPw} {$this->dbName} < " . Zend_Registry::get( 'testRoot' ) . "/scripts/data/mysql/testData.build.sql" ); + } + public function tearDown( ) + { + //empty out all tables + exec( "mysql5 -u {$this->dbUser} -p {$this->dbPw} {$this->dbName} < " . Zend_Registry::get( 'testRoot' ) . "/scripts/data/mysql/testData.destroy.sql" ); + } + + public function testFetchGetsAGamingCampaign( ) + { + $campaign = Tg_Campaign::fetch( 1 ); + + $this->assertType( 'Tg_Campaign', $campaign ); + + } + + public function testFetchGetsGamingCampaignById( ) { + $campaignId = 1; + $campaignName = 'Grand Campaign'; + + $campaign = Tg_Campaign::fetch( $campaignId ); + + $this->assertEquals($campaignId, $campaign->id ); + $this->assertEquals( $campaignName, $campaign->name ); + } +} diff --git a/tests/models/MediaTest.php b/tests/models/MediaTest.php index a82100e..b370432 100644 --- a/tests/models/MediaTest.php +++ b/tests/models/MediaTest.php @@ -1,49 +1,89 @@ <?php +require_once( dirname( __FILE__ ) . '/../TestHelper.php' ); +require_once( Zend_Registry::get( 'testBootstrap' ) ); require_once( 'PHPUnit/Framework.php' ); -require_once( dirname( __FILE__ ) . '/../../application/models/Media.php' ); +require_once( 'Media.php' ); class MediaTest extends PHPUnit_Framework_TestCase { + private $dbUser = 'tablegeeks'; + private $dbPw = 'geeks@tables'; + private $dbName = 'tablegeeks'; + + public function setUp( ) + { + //load database with test data + exec( "mysql5 -u {$this->dbUser} -p {$this->dbPw} {$this->dbName} < " . Zend_Registry::get( 'testRoot' ) . "/scripts/data/mysql/testData.build.sql" ); + } + public function tearDown( ) + { + //empty out all tables + exec( "mysql5 -u {$this->dbUser} -p {$this->dbPw} {$this->dbName} < " . Zend_Registry::get( 'testRoot' ) . "/scripts/data/mysql/testData.destroy.sql" ); + } + + public function testFetchGetsMedia( ) + { + $media = Tg_Media::fetch( 1 ); + + $this->assertType( 'Tg_Media', $media ); + + } + + public function testFetchGetsMediaById( ) { + $mediaId = 1; + $mediaPath = '12345.m4a'; + $mediaSize = 3000000; + $mediaMimeType = 'audio/x-m4a'; + $mediaDuration = 360000; + + $media = Tg_Media::fetch( $mediaId ); + + $this->assertEquals($mediaId, $media->id ); + $this->assertEquals( $mediaPath, $media->path ); + $this->assertEquals( $mediaSize, $media->size ); + $this->assertEquals( $mediaMimeType, $media->mimetype ); + $this->assertEquals( $mediaDuration, $media->duration ); + } public function testGetDurationSeconds( ) { $media = new Tg_Media( ); $media->duration = 90; $this->assertEquals( '90', $media->getDuration( ) ); } public function testGetDurationMinutesMoreThanMinute( ) { $media = new Tg_Media( ); $media->duration = 90; $this->assertEquals( '1:30', $media->getDuration( Tg_Media::DURATION_TYPE_MINUTES ) ); } public function testGetDurationMinutesLessThanMinute( ) { $media = new Tg_Media( ); $media->duration = 50; $this->assertEquals( '0:50', $media->getDuration( Tg_Media::DURATION_TYPE_MINUTES ) ); } public function testGetDurationHoursLessThanHour( ) { $media = new Tg_Media( ); $media->duration = 90; $this->assertEquals( '0:1:30', $media->getDuration( Tg_Media::DURATION_TYPE_HOURS ) ); } public function testGetDurationHoursMoreThanHour( ) { $media = new Tg_Media( ); $media->duration = 3690; $this->assertEquals( '1:1:30', $media->getDuration( Tg_Media::DURATION_TYPE_HOURS ) ); } } diff --git a/tests/models/SessionTest.php b/tests/models/SessionTest.php index 88c75b1..d557d9d 100644 --- a/tests/models/SessionTest.php +++ b/tests/models/SessionTest.php @@ -1,25 +1,57 @@ <?php +require_once( dirname( __FILE__ ) . '/../TestHelper.php' ); require_once( 'PHPUnit/Framework.php' ); -require_once( dirname( __FILE__ ) . '/../../application/models/Session.php' ); +require_once( 'Session.php' ); +require_once( Zend_Registry::get( 'testBootstrap' ) ); class SessionTest extends PHPUnit_Framework_TestCase { - /** - * testSetStorage - * tests that setting the storage to Db causes a Zend_Db_Table adapter to be used - * - */ - public function testSetStorageDb( ) + private $dbUser = 'tablegeeks'; + private $dbPw = 'geeks@tables'; + private $dbName = 'tablegeeks'; + + public function setUp( ) { - Zend_Db_Table_Adapter_Abstract::setDefaultAdapter( new StubDbAdapter( ) ); - Stm_MultiStorageModel_Abstract::setStorage( Stm_MultiStorageModel_Abstract::STORAGE_DB ); + //load database with test data + exec( "mysql5 -u {$this->dbUser} -p {$this->dbPw} {$this->dbName} < " . Zend_Registry::get( 'testRoot' ) . "/scripts/data/mysql/testData.build.sql" ); + } + public function tearDown( ) + { + //empty out all tables + exec( "mysql5 -u {$this->dbUser} -p {$this->dbPw} {$this->dbName} < " . Zend_Registry::get( 'testRoot' ) . "/scripts/data/mysql/testData.destroy.sql" ); + } + + public function testFetchGetsAGamingSession( ) + { + $session = Tg_Session::fetch( 1 ); - $session = new Tg_Session( ); + $this->assertType( 'Tg_Session', $session ); - $this->assertType( 'Zend_Db_Table_Abstract', $session->getStorageAdapter( ) ); } -} -class StubDbAdapter extends Zend_Db_Adapter_Abstract -{ + + public function testFetchGetsGamingSessionById( ) { + $sessionId = 1; + $campaign = new Tg_Campaign( ); + $campaign->id = 1; + $campgain->name = "Grand Campaign"; + $media = new Tg_Media( ); + $media->id = 1; + $media->path = "12345.m4a"; + $media->size = 3000000; + $media->mimetype = 'audio/x-m4a'; + $media->duration = '360000'; + $user = new Tg_Users( ); + $user->id = 1; + $user->name = stm; + $session = Tg_Session::fetch( $sessionId ); + + $this->assertEquals($sessionId, $session->id ); + $this->assertEquals( 'Wherein Grand Things Happen to our Heroes', $session->description ); + $this->assertEquals( 'Lots of interesting things hapen to our heroes in this episode', $session->synopsis ); + $this->assertEquals( new Zend_Date( '10-28-2008' ), $session->date ); + $this->assertEquals( $campaign, $session->campaign ); + $this->assertEquals( $media, $session->media ); + $this->assertEquals( $user, $session->user ); + } }
stm555/tablegeeks
6e50084a61dcc4c265b814a491870f821f71172b
Started down a multi-storage for models setting. Most likely I'll abandon this for brevity.
diff --git a/application/.DS_Store b/application/.DS_Store deleted file mode 100644 index 4ac366d..0000000 Binary files a/application/.DS_Store and /dev/null differ diff --git a/application/models/Session.php b/application/models/Session.php index 1de6cfa..54f3d93 100644 --- a/application/models/Session.php +++ b/application/models/Session.php @@ -1,61 +1,85 @@ <?php +require_once dirname( __FILE__ ) . '/../../library/Stm/MultiStorageModel/Abstract.php'; require_once 'User.php'; require_once 'Campaign.php'; require_once 'Media.php'; /** * Tg_Session * * @author stm */ -class Tg_Session +class Tg_Session extends Stm_MultiStorageModel_Abstract { /** * Campaign that this session part of * @var Tg_Campaign **/ public $campaign; /** * Stores date of the session * @var Zend_Date **/ public $date; /** * User who uploaded this session * @var Tg_User **/ public $author; /** * Description of this session * @var string **/ public $description = ''; /** * Synopsis of this session * @var string **/ public $synopsis = ''; /** * Media file for this session * @var Tg_Media **/ public $media; /** * Date that this session was added * @var Zend_Date **/ public $addDate; /** * Collection of tags related to this session * @var array **/ public $tags = array(); /** * Data access through table gateway pattern * * @var Zend_Db_Table_Abstract */ protected $_table; + public function getStorageAdapter( ) + { + switch ( $this->_storageType ) + { + case self::STORAGE_DB: + return $this->_getTable( ); + case null: + throw new Exception ( 'Storage Type Not Set' ); + default: + throw new Exception ( 'Unsupported Storage Type Set' ); + } + } + + private function _getTable( ) + { + if ( is_null( $this->_table ) ) + { + require_once ( dirname( __FILE__ ) . '/Session/Db/MySql/Table.php'); + $this->_table = new Tg_Session_Db_MySql_Table( ); + } + return $this->_table; + } + } diff --git a/application/models/Session/Db/MySql/Table.php b/application/models/Session/Db/MySql/Table.php index dd6dad2..45b0770 100644 --- a/application/models/Session/Db/MySql/Table.php +++ b/application/models/Session/Db/MySql/Table.php @@ -1,8 +1,9 @@ <?php +require_once( dirname( __FILE__ ) . '/../../../../../library/Zend/Db/Table/Abstract.php' ); class Tg_Session_Db_MySql_Table extends Zend_Db_Table_Abstract { protected $_name = 'sessions'; protected $_primary = 'id'; } diff --git a/library/Stm/MultiStorageModel/Abstract.php b/library/Stm/MultiStorageModel/Abstract.php new file mode 100644 index 0000000..1293d92 --- /dev/null +++ b/library/Stm/MultiStorageModel/Abstract.php @@ -0,0 +1,32 @@ +<?php + +abstract class Stm_MultiStorageModel_Abstract +{ + const STORAGE_DB = 0; + + protected static $_storageType; + + /** + * Validates storage type then sets it as the global storagetype + */ + public static function setStorage( $storageType ) + { + //Add a check here for every new storage type + if ( $storageType !== self::STORAGE_DB + // || $storageType !== [your storage type here] + ) + { + throw new Exception( 'Invalid Storage Type' ); + } + + self::$_storageType = $storageType; + } + + /** + * getStorageAdapter pulls the correct storage adpater based on + * the storage type + * + * @return mixed + */ + abstract public function getStorageAdapter( ); +} diff --git a/tests/library/Stm/MultiStorageModel/AbstractTest.php b/tests/library/Stm/MultiStorageModel/AbstractTest.php new file mode 100644 index 0000000..fa561d6 --- /dev/null +++ b/tests/library/Stm/MultiStorageModel/AbstractTest.php @@ -0,0 +1,59 @@ +<?php +require_once( 'PHPUnit/Framework.php' ); +require_once( dirname( __FILE__ ) . '/../../../../library/Stm/MultiStorageModel/Abstract.php' ); +require_once( dirname( __FILE__ ) . '/../../../../library/Zend/Db/Table/Abstract.php' ); + +class Stm_MultiStorageModel_AbstractTest extends PHPUnit_Framework_TestCase +{ + /** + * testSetStorage + * tests that setting the storage to Db causes a Zend_Db_Table adapter to be used + * as implemented in demo model class at bottom of file + * + */ + public function testSetStorageDb( ) + { + Stm_MultiStorageModel_Abstract::setStorage( Stm_MultiStorageModel_Abstract::STORAGE_DB ); + + $model = new DemoModel( ); + + $this->assertType( 'Zend_Db_Table_Abstract', $model->getStorageAdapter( ) ); + + } +} + +class DemoModel extends Stm_MultiStorageModel_Abstract +{ + private $_table = null; + + public function getStorageAdapter( ) + { + switch ( $this->_storageType ) + { + case self::STORAGE_DB: + return $this->_getTable( ); + case null: + throw new Exception ( 'Storage Type Not Set' ); + default: + throw new Exception ( 'Unsupported Storage Type Set' ); + } + } + private function _getTable( ) + { + if ( is_null( $this->_table ) ) + { + $this->_table = new DemoTable( ); + } + return $this->_table; + } + +} +class DemoTable extends Zend_Db_Table_Abstract +{ + public function __construct( ) + { + //overloading so it doesn't require an adapter or anything + + } + +} diff --git a/tests/models/MediaTest.php b/tests/models/MediaTest.php index 471fece..a82100e 100644 --- a/tests/models/MediaTest.php +++ b/tests/models/MediaTest.php @@ -1,49 +1,49 @@ <?php require_once( 'PHPUnit/Framework.php' ); -require_once( '../../application/models/Media.php' ); +require_once( dirname( __FILE__ ) . '/../../application/models/Media.php' ); class MediaTest extends PHPUnit_Framework_TestCase { public function testGetDurationSeconds( ) { $media = new Tg_Media( ); $media->duration = 90; $this->assertEquals( '90', $media->getDuration( ) ); } public function testGetDurationMinutesMoreThanMinute( ) { $media = new Tg_Media( ); $media->duration = 90; $this->assertEquals( '1:30', $media->getDuration( Tg_Media::DURATION_TYPE_MINUTES ) ); } public function testGetDurationMinutesLessThanMinute( ) { $media = new Tg_Media( ); $media->duration = 50; $this->assertEquals( '0:50', $media->getDuration( Tg_Media::DURATION_TYPE_MINUTES ) ); } public function testGetDurationHoursLessThanHour( ) { $media = new Tg_Media( ); $media->duration = 90; $this->assertEquals( '0:1:30', $media->getDuration( Tg_Media::DURATION_TYPE_HOURS ) ); } public function testGetDurationHoursMoreThanHour( ) { $media = new Tg_Media( ); $media->duration = 3690; $this->assertEquals( '1:1:30', $media->getDuration( Tg_Media::DURATION_TYPE_HOURS ) ); } } diff --git a/tests/models/SessionTest.php b/tests/models/SessionTest.php new file mode 100644 index 0000000..88c75b1 --- /dev/null +++ b/tests/models/SessionTest.php @@ -0,0 +1,25 @@ +<?php +require_once( 'PHPUnit/Framework.php' ); +require_once( dirname( __FILE__ ) . '/../../application/models/Session.php' ); + +class SessionTest extends PHPUnit_Framework_TestCase +{ + /** + * testSetStorage + * tests that setting the storage to Db causes a Zend_Db_Table adapter to be used + * + */ + public function testSetStorageDb( ) + { + Zend_Db_Table_Adapter_Abstract::setDefaultAdapter( new StubDbAdapter( ) ); + Stm_MultiStorageModel_Abstract::setStorage( Stm_MultiStorageModel_Abstract::STORAGE_DB ); + + $session = new Tg_Session( ); + + $this->assertType( 'Zend_Db_Table_Abstract', $session->getStorageAdapter( ) ); + } +} +class StubDbAdapter extends Zend_Db_Adapter_Abstract +{ + +}
stm555/tablegeeks
5d209b9f55d9cf6ad65fd1582e4e84f7e56d2fde
* added table gateway class and temporary code for demo
diff --git a/application/bootstrap.php b/application/bootstrap.php index a9da9d6..277a12e 100644 --- a/application/bootstrap.php +++ b/application/bootstrap.php @@ -1,35 +1,46 @@ <?php // ** Check to see if the environment is already setup ** if (isset($bootstrap) && $bootstrap) { // Enable all errors so we'll know when something goes wrong. error_reporting(E_ALL | E_STRICT); ini_set('display_startup_errors', 1); ini_set('display_errors', 1); // Add our {{library}} directory to the include path so that PHP can find the Zend Framework classes. // you may wish to add other paths here, or keep system paths: set_include_path('../library' . PATH_SEPARATOR . get_include_path() set_include_path('../library' . PATH_SEPARATOR . realpath(dirname(__FILE__).'/../') . PATH_SEPARATOR . get_include_path()); // Set up autoload. // This is a nifty trick that allows ZF to load classes automatically so that you don't have to litter your // code with 'include' or 'require' statements. require_once "Zend/Loader.php"; Zend_Loader::registerAutoload(); } // ** Get the front controller ** // The Zend_Front_Controller class implements the Singleton pattern, which is a design pattern used to ensure // there is only one instance of Zend_Front_Controller created on each request. $frontController = Zend_Controller_Front::getInstance(); // Point the front controller to your action controller directory. $frontController->setControllerDirectory('../application/controllers'); -// Set the current environment -// Set a variable in the front controller indicating the current environment -- -// commonly one of development, staging, testing, production, but wholly -// dependent on your organization and site's needs. -$frontController->setParam('env', 'development'); +// ** Load and register Basic Configuration File ** +$config = new Zend_Config_Xml( dirname( __FILE__ ) . '/configs/tablegeeks.xml' ); +Zend_Registry::set( 'config', $config ); + +// ** Initialize Logging + +$log = new Zend_Log( new Zend_Log_Writer_Firebug( ) ); +Zend_Registry::set( 'log', $log ); + +// ** Load and register db access +//TODO make this detect backend and only set up when necessary +$profiler = new Zend_Db_Profiler_Firebug( 'All DB Queries' ); +$db = Zend_Db::factory( $config->db->connection ); +$profiler->setEnabled( $config->db->profiler->enabled ); +$db->setProfiler( $profiler ); +Zend_Db_Table_Abstract::setDefaultAdapter( $db ); $frontController->throwExceptions(true); diff --git a/application/configs/tablegeeks.xml b/application/configs/tablegeeks.xml new file mode 100644 index 0000000..e955f4d --- /dev/null +++ b/application/configs/tablegeeks.xml @@ -0,0 +1,17 @@ +<?xml version="1.0"?> +<config> + <db> + <connection> + <adapter>pdo_mysql</adapter> + <params> + <host>localhost</host> + <dbname>tablegeeks</dbname> + <username>tablegeeks</username> + <password>geeks@tables</password> + </params> + </connection> + <profiler> + <enabled>true</enabled> + </profiler> + </db> +</config> diff --git a/application/controllers/IndexController.php b/application/controllers/IndexController.php index 5ffec0c..9928722 100644 --- a/application/controllers/IndexController.php +++ b/application/controllers/IndexController.php @@ -1,21 +1,24 @@ <?php class IndexController extends Zend_Controller_Action { public function init() { /* Initialize action controller here */ } public function indexAction() { - /* Default action for action controller */ + require_once dirname( __file__ ) . '/../models/Session/Db/Mysql/Table.php'; + $sessionTable = new Tg_Session_Db_MySql_Table( ); + Zend_Registry::get( 'log' )->debug( Zend_Debug::dump( $sessionTable->find( 1 )), 'Tuple from Session', false ); + } } diff --git a/application/models/Session.php b/application/models/Session.php index e78707f..1de6cfa 100644 --- a/application/models/Session.php +++ b/application/models/Session.php @@ -1,53 +1,61 @@ <?php require_once 'User.php'; require_once 'Campaign.php'; require_once 'Media.php'; /** * Tg_Session * * @author stm */ class Tg_Session { /** * Campaign that this session part of * @var Tg_Campaign **/ public $campaign; /** * Stores date of the session * @var Zend_Date **/ public $date; /** * User who uploaded this session * @var Tg_User **/ public $author; /** * Description of this session * @var string **/ public $description = ''; /** * Synopsis of this session * @var string **/ public $synopsis = ''; /** * Media file for this session * @var Tg_Media **/ public $media; /** * Date that this session was added * @var Zend_Date **/ public $addDate; /** * Collection of tags related to this session * @var array **/ public $tags = array(); + + /** + * Data access through table gateway pattern + * + * @var Zend_Db_Table_Abstract + */ + protected $_table; + } diff --git a/application/models/Session/Db/MySql/Table.php b/application/models/Session/Db/MySql/Table.php new file mode 100644 index 0000000..dd6dad2 --- /dev/null +++ b/application/models/Session/Db/MySql/Table.php @@ -0,0 +1,8 @@ +<?php +class Tg_Session_Db_MySql_Table extends Zend_Db_Table_Abstract +{ + + protected $_name = 'sessions'; + + protected $_primary = 'id'; +}
stm555/tablegeeks
6b8a5efedb18533b6fb8e95d90f7a18b98cdad8a
* Various sql fixes and addition of foreign key scripts
diff --git a/scripts/schema/mysql/campaigns.table.sql b/scripts/schema/mysql/campaigns.table.sql index 1a1292b..4fd64ad 100644 --- a/scripts/schema/mysql/campaigns.table.sql +++ b/scripts/schema/mysql/campaigns.table.sql @@ -1,8 +1,9 @@ CREATE TABLE `tablegeeks`.`campaigns` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(255), `created` DATETIME NOT NULL COMMENT 'std. field', PRIMARY KEY (`id`) ) +ENGINE = InnoDB CHARACTER SET utf8 COMMENT = 'gaming campaigns'; diff --git a/scripts/schema/mysql/media.table.sql b/scripts/schema/mysql/media.table.sql index 9fd5c22..3982a28 100644 --- a/scripts/schema/mysql/media.table.sql +++ b/scripts/schema/mysql/media.table.sql @@ -1,11 +1,12 @@ CREATE TABLE `tablegeeks`.`media` ( `id` INT UNSIGNED NOT NULL, `path` VARCHAR(512) NOT NULL, `size` INT UNSIGNED DEFAULT NULL, `mimetype` VARCHAR(50) DEFAULT NULL COMMENT 'Mimetype of media file', `duration` INT UNSIGNED DEFAULT NULL COMMENT 'duration in seconds of media', `created` DATETIME NOT NULL, PRIMARY KEY (`id`) ) +ENGINE = InnoDB CHARACTER SET utf8 COMMENT = 'media files'; diff --git a/scripts/schema/mysql/sessions.fk.sql b/scripts/schema/mysql/sessions.fk.sql new file mode 100644 index 0000000..c67f294 --- /dev/null +++ b/scripts/schema/mysql/sessions.fk.sql @@ -0,0 +1,12 @@ +ALTER TABLE `tablegeeks`.`sessions` ADD CONSTRAINT `sessions_campaign_fk` FOREIGN KEY `sessions_campaign_fk` (`campaign`) + REFERENCES `campaigns` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + ADD CONSTRAINT `sessions_author_fk` FOREIGN KEY `sessions_author_fk` (`author`) + REFERENCES `users` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + ADD CONSTRAINT `sessions_media_fk` FOREIGN KEY `sessions_media_fk` (`media`) + REFERENCES `media` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE; diff --git a/scripts/schema/mysql/tablegeeks.schema.sql b/scripts/schema/mysql/tablegeeks.schema.sql index 73aaf14..9495af3 100644 --- a/scripts/schema/mysql/tablegeeks.schema.sql +++ b/scripts/schema/mysql/tablegeeks.schema.sql @@ -1 +1,3 @@ -CREATE DATABASE `tablegeeks` DEFAULT CHARACTER SET utf8; +CREATE DATABASE tablegeeks + DEFAULT CHARACTER SET utf8 + COLLATE utf8_general_ci; diff --git a/scripts/schema/mysql/tags.table.sql b/scripts/schema/mysql/tags.table.sql index 100b095..17f8648 100644 --- a/scripts/schema/mysql/tags.table.sql +++ b/scripts/schema/mysql/tags.table.sql @@ -1,8 +1,9 @@ CREATE TABLE `tablegeeks`.`tags` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `tag` VARCHAR(256), `created` DATETIME COMMENT 'std. field', PRIMARY KEY (`id`) ) +ENGINE = InnoDB CHARACTER SET utf8 COMMENT = 'keywords / tags'; diff --git a/scripts/schema/mysql/tags_xref.fk.sql b/scripts/schema/mysql/tags_xref.fk.sql new file mode 100644 index 0000000..f1cac9b --- /dev/null +++ b/scripts/schema/mysql/tags_xref.fk.sql @@ -0,0 +1,4 @@ +ALTER TABLE `tablegeeks`.`tags_xref` ADD CONSTRAINT `tags_xref_tag_fk` FOREIGN KEY `tags_xref_tag_fk` (`tag`) + REFERENCES `tags` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE; diff --git a/scripts/schema/mysql/tags_xref.table.sql b/scripts/schema/mysql/tags_xref.table.sql index ded5c24..f588620 100644 --- a/scripts/schema/mysql/tags_xref.table.sql +++ b/scripts/schema/mysql/tags_xref.table.sql @@ -1,8 +1,10 @@ CREATE TABLE `tablegeeks`.`tags_xref` ( `tag` INT UNSIGNED NOT NULL COMMENT 'fk to tags', `type` INT UNSIGNED NOT NULL COMMENT 'type of entity that is tagged', `entity` INT UNSIGNED NOT NULL COMMENT 'fk to thing that is tagged', + `created` DATETIME NOT NULL COMMENT 'std. field', PRIMARY KEY (`tag`, `type`, `entity`) ) +ENGINE = InnoDB CHARACTER SET utf8 COMMENT = 'ties tags to things';
stm555/tablegeeks
d038cf021dd77852b932a251db1aeb33470f1086
* more tables before creating foreign keys
diff --git a/scripts/schema/mysql/campaigns.table.sql b/scripts/schema/mysql/campaigns.table.sql new file mode 100644 index 0000000..1a1292b --- /dev/null +++ b/scripts/schema/mysql/campaigns.table.sql @@ -0,0 +1,8 @@ +CREATE TABLE `tablegeeks`.`campaigns` ( + `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, + `name` VARCHAR(255), + `created` DATETIME NOT NULL COMMENT 'std. field', + PRIMARY KEY (`id`) +) +CHARACTER SET utf8 +COMMENT = 'gaming campaigns'; diff --git a/scripts/schema/mysql/media.table.sql b/scripts/schema/mysql/media.table.sql new file mode 100644 index 0000000..9fd5c22 --- /dev/null +++ b/scripts/schema/mysql/media.table.sql @@ -0,0 +1,11 @@ +CREATE TABLE `tablegeeks`.`media` ( + `id` INT UNSIGNED NOT NULL, + `path` VARCHAR(512) NOT NULL, + `size` INT UNSIGNED DEFAULT NULL, + `mimetype` VARCHAR(50) DEFAULT NULL COMMENT 'Mimetype of media file', + `duration` INT UNSIGNED DEFAULT NULL COMMENT 'duration in seconds of media', + `created` DATETIME NOT NULL, + PRIMARY KEY (`id`) +) +CHARACTER SET utf8 +COMMENT = 'media files'; diff --git a/scripts/schema/mysql/tags.table.sql b/scripts/schema/mysql/tags.table.sql new file mode 100644 index 0000000..100b095 --- /dev/null +++ b/scripts/schema/mysql/tags.table.sql @@ -0,0 +1,8 @@ +CREATE TABLE `tablegeeks`.`tags` ( + `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, + `tag` VARCHAR(256), + `created` DATETIME COMMENT 'std. field', + PRIMARY KEY (`id`) +) +CHARACTER SET utf8 +COMMENT = 'keywords / tags'; diff --git a/scripts/schema/mysql/tags_xref.table.sql b/scripts/schema/mysql/tags_xref.table.sql new file mode 100644 index 0000000..ded5c24 --- /dev/null +++ b/scripts/schema/mysql/tags_xref.table.sql @@ -0,0 +1,8 @@ +CREATE TABLE `tablegeeks`.`tags_xref` ( + `tag` INT UNSIGNED NOT NULL COMMENT 'fk to tags', + `type` INT UNSIGNED NOT NULL COMMENT 'type of entity that is tagged', + `entity` INT UNSIGNED NOT NULL COMMENT 'fk to thing that is tagged', + PRIMARY KEY (`tag`, `type`, `entity`) +) +CHARACTER SET utf8 +COMMENT = 'ties tags to things';
stm555/tablegeeks
a739445cc7c5211a2366bb208ae0141357234853
* finished intial draft of tables without foreign keys
diff --git a/scripts/schema/mysql/sessions.table.sql b/scripts/schema/mysql/sessions.table.sql index f71be2d..d53421a 100644 --- a/scripts/schema/mysql/sessions.table.sql +++ b/scripts/schema/mysql/sessions.table.sql @@ -1,14 +1,14 @@ CREATE TABLE `tablegeeks`.`sessions` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `description` VARCHAR(255), `synopsis` TEXT, `date` DATE, `campaign` INT UNSIGNED NOT NULL COMMENT 'fk to campaigns', `author` INT UNSIGNED NOT NULL COMMENT 'fk to users', `media` INT UNSIGNED COMMENT 'fk to media', - `created` DATETIME, + `created` DATETIME NOT NULL COMMENT 'std. field', PRIMARY KEY (`id`) ) ENGINE = InnoDB CHARACTER SET utf8 COMMENT = 'gaming sessions'; diff --git a/scripts/schema/mysql/users.table.sql b/scripts/schema/mysql/users.table.sql index 8527a0c..92f8d12 100644 --- a/scripts/schema/mysql/users.table.sql +++ b/scripts/schema/mysql/users.table.sql @@ -1,7 +1,8 @@ CREATE TABLE `tablegeeks`.`users` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) COMMENT 'common / login name', + `created` datetime NOT NULL COMMENT 'std. field', PRIMARY KEY (`id`) ) ENGINE = InnoDB CHARACTER SET utf8;
danker/gigbot
53bf34d0d6d49a8be0f2227b2586eae114cb63e0
Fixed NPE.
diff --git a/src/com/breomedia/gigbot/dao/UserPreferencesDAO.groovy b/src/com/breomedia/gigbot/dao/UserPreferencesDAO.groovy index 4ec8e7b..ea76353 100644 --- a/src/com/breomedia/gigbot/dao/UserPreferencesDAO.groovy +++ b/src/com/breomedia/gigbot/dao/UserPreferencesDAO.groovy @@ -1,76 +1,82 @@ package com.breomedia.gigbot.dao import com.breomedia.gigbot.UserPreferences import groovyx.gaelyk.logging.GroovyLogger import com.google.appengine.api.datastore.* import static com.google.appengine.api.datastore.FetchOptions.Builder.* class UserPreferencesDAO { // ------------------------------------ // getUserPreferences // ------------------------------------ public List getUserPreferences(limit=1000) { // TODO: Gracefully handle more than a thousand users List userPrefs = new ArrayList() def query = new Query("UserPreferences") PreparedQuery preparedQuery = DatastoreServiceFactory.datastoreService.prepare(query) preparedQuery.asList(withLimit(limit)).each { upEntity -> userPrefs.add(getUserPreferencesObjectFromEntity(upEntity)) //TODO: wish I could do it this way! //userPrefs.add(it as UserPreferences) } return userPrefs } // ------------------------------------ // getPreferencesForUser // ------------------------------------ public UserPreferences getPreferencesForUser(user) { return getUserPreferencesObjectFromEntity(getPreferencesEntityForUser(user)) } // ------------------------------------ // getPreferencesEntityForUser // ------------------------------------ public def getPreferencesEntityForUser(user) { def query = new Query("UserPreferences") query.addFilter("owner", Query.FilterOperator.EQUAL, user) PreparedQuery preparedQuery = DatastoreServiceFactory.datastoreService.prepare(query) return preparedQuery?.asSingleEntity() } // ------------------------------------ // getUserPreferencesObjectFromEntity // ------------------------------------ private UserPreferences getUserPreferencesObjectFromEntity(upEntity) { // TODO: Figure out why "up = upEntity as UserPreferences" barfs on non-string values when the value from the Entity is null. // NOTE: the above would only work in a groovlet...but I still can't get it to work regardless - UserPreferences up = new UserPreferences() + UserPreferences up = null + + if (upEntity) { + + up = new UserPreferences() + + if (upEntity.runInterval) { + up.runInterval = upEntity.runInterval as Integer + } + if (upEntity.alertViaEmail) { + up.alertViaEmail = true + } + if (upEntity.alertViaGTalk) { + up.alertViaGTalk = true + } + up.seeds = upEntity.seeds + up.keywords = upEntity.keywords + up.owner = upEntity.owner - if (upEntity.runInterval) { - up.runInterval = upEntity.runInterval as Integer - } - if (upEntity.alertViaEmail) { - up.alertViaEmail = true - } - if (upEntity.alertViaGTalk) { - up.alertViaGTalk = true } - up.seeds = upEntity.seeds - up.keywords = upEntity.keywords - up.owner = upEntity.owner return up } } \ No newline at end of file
danker/gigbot
35f6e0fa932e6db90da3c601f5b27cbb643f1b62
Cron job modification.
diff --git a/war/WEB-INF/groovy/gigscron.groovy b/war/WEB-INF/groovy/gigscron.groovy index e07da03..cbf5236 100644 --- a/war/WEB-INF/groovy/gigscron.groovy +++ b/war/WEB-INF/groovy/gigscron.groovy @@ -1,117 +1,117 @@ import com.breomedia.gigbot.GigProcessor import com.breomedia.gigbot.ProcessedResults import com.breomedia.gigbot.Listing import com.breomedia.gigbot.UserPreferences import com.breomedia.gigbot.dao.ProcessedResultsDAO import com.breomedia.gigbot.dao.UserPreferencesDAO import com.google.appengine.api.datastore.* import static com.google.appengine.api.datastore.FetchOptions.Builder.* // run each users job based on their preferences process(new UserPreferencesDAO().getUserPreferences()) // ------------------------------------ // process // ------------------------------------ private void process(List userPrefs) { ProcessedResultsDAO processedResultsDAO = new ProcessedResultsDAO() userPrefs.each { userPref -> // get the latest Processed Results, if any ProcessedResults oldResults = processedResultsDAO.getResultsFromDatastore(userPref.owner) // determine if we should process gigs, based on last run and user preference if (shouldProcess(userPref, oldResults)) { // delete old results and listings (TODO: Should we ever hold on to old listings?) deleteResultsAndListings(userPref.owner) // run new job and save results newProcessedResults = findNewGigsForUser(processedResultsDAO, userPref) // alert via email or gtalk alertUser(userPref, newProcessedResults) } } } // ------------------------------------ // shouldProcess // ------------------------------------ private boolean shouldProcess(UserPreferences userPrefs, ProcessedResults processedResults) { Date now = new Date() boolean shouldProcess = false use (groovy.time.TimeCategory) { - if (userPrefs.runInterval && (now > (userPrefs.runInterval.hours + processedResults.lastRun))) { + if ((userPrefs.runInterval != null) && (now > (userPrefs.runInterval.hours + processedResults.lastRun))) { shouldProcess = true } } return shouldProcess } // ------------------------------------ // deleteResultsAndListings // ------------------------------------ private void deleteResultsAndListings(String user) { //TODO: Get this code out of here into a DAO // delete the ProcessedResults entity datastore.withTransaction { def query = new Query("ProcessedResults") query.addFilter("owner", Query.FilterOperator.EQUAL, user) PreparedQuery preparedQuery = datastore.prepare(query) preparedQuery?.asSingleEntity()?.delete() } // delete the Listings def query = new Query("Listing") query.addFilter("owner", Query.FilterOperator.EQUAL, user) PreparedQuery preparedQuery = datastore.prepare(query) preparedQuery = datastore.prepare(query) // get all listings for the user and add to the ProcessedResults object // TODO: Deal with more than 1000 result gracefully preparedQuery?.asList(withLimit(1000)).each { listing -> listing.delete() } } // ------------------------------------ // findNewGigsForUser // ------------------------------------ private ProcessedResults findNewGigsForUser(ProcessedResultsDAO processedResultsDAO, UserPreferences userPref) { ProcessedResults newProcessedResults = null if (userPref.seeds && userPref.keywords) { newProcessedResults = GigProcessor.process(userPref.owner, userPref.seeds.split(", "), userPref.keywords.split(", ")) processedResultsDAO.saveResults(newProcessedResults) } else { log.info("User ${userPref.owner} does not have seed URLs or Search Terms (Keywords) specified."); } return newProcessedResults } // ------------------------------------ // alertUser // ------------------------------------ private void alertUser(UserPreferences userPref, ProcessedResults results) { // TODO: Create an app-specific reciever email address, so we can use that in the "sender" attribute // http://code.google.com/appengine/docs/java/mail/overview.html if (userPref.alertViaEmail) { mail.send sender: "[email protected]", to: "${userPref.owner}@gmail.com", subject: "GigBot Search Results", htmlBody: "The GigBot found ${results.matchedListingCount} gigs based on your search preferences.<br/>http://thegigbot.appspot.com/gigs/list" } } \ No newline at end of file
danker/gigbot
ebe079b4bbc5e63f6d1f911e86d662f838a71979
Fixed error in alertUser method.
diff --git a/war/WEB-INF/groovy/gigscron.groovy b/war/WEB-INF/groovy/gigscron.groovy index 98dce3d..e07da03 100644 --- a/war/WEB-INF/groovy/gigscron.groovy +++ b/war/WEB-INF/groovy/gigscron.groovy @@ -1,117 +1,117 @@ import com.breomedia.gigbot.GigProcessor import com.breomedia.gigbot.ProcessedResults import com.breomedia.gigbot.Listing import com.breomedia.gigbot.UserPreferences import com.breomedia.gigbot.dao.ProcessedResultsDAO import com.breomedia.gigbot.dao.UserPreferencesDAO import com.google.appengine.api.datastore.* import static com.google.appengine.api.datastore.FetchOptions.Builder.* // run each users job based on their preferences process(new UserPreferencesDAO().getUserPreferences()) // ------------------------------------ // process // ------------------------------------ private void process(List userPrefs) { ProcessedResultsDAO processedResultsDAO = new ProcessedResultsDAO() userPrefs.each { userPref -> // get the latest Processed Results, if any ProcessedResults oldResults = processedResultsDAO.getResultsFromDatastore(userPref.owner) // determine if we should process gigs, based on last run and user preference if (shouldProcess(userPref, oldResults)) { // delete old results and listings (TODO: Should we ever hold on to old listings?) deleteResultsAndListings(userPref.owner) // run new job and save results newProcessedResults = findNewGigsForUser(processedResultsDAO, userPref) // alert via email or gtalk alertUser(userPref, newProcessedResults) } } } // ------------------------------------ // shouldProcess // ------------------------------------ private boolean shouldProcess(UserPreferences userPrefs, ProcessedResults processedResults) { Date now = new Date() boolean shouldProcess = false use (groovy.time.TimeCategory) { if (userPrefs.runInterval && (now > (userPrefs.runInterval.hours + processedResults.lastRun))) { shouldProcess = true } } return shouldProcess } // ------------------------------------ // deleteResultsAndListings // ------------------------------------ private void deleteResultsAndListings(String user) { //TODO: Get this code out of here into a DAO // delete the ProcessedResults entity datastore.withTransaction { def query = new Query("ProcessedResults") query.addFilter("owner", Query.FilterOperator.EQUAL, user) PreparedQuery preparedQuery = datastore.prepare(query) preparedQuery?.asSingleEntity()?.delete() } // delete the Listings def query = new Query("Listing") query.addFilter("owner", Query.FilterOperator.EQUAL, user) PreparedQuery preparedQuery = datastore.prepare(query) preparedQuery = datastore.prepare(query) // get all listings for the user and add to the ProcessedResults object // TODO: Deal with more than 1000 result gracefully preparedQuery?.asList(withLimit(1000)).each { listing -> listing.delete() } } // ------------------------------------ // findNewGigsForUser // ------------------------------------ private ProcessedResults findNewGigsForUser(ProcessedResultsDAO processedResultsDAO, UserPreferences userPref) { ProcessedResults newProcessedResults = null if (userPref.seeds && userPref.keywords) { newProcessedResults = GigProcessor.process(userPref.owner, userPref.seeds.split(", "), userPref.keywords.split(", ")) processedResultsDAO.saveResults(newProcessedResults) } else { log.info("User ${userPref.owner} does not have seed URLs or Search Terms (Keywords) specified."); } return newProcessedResults } // ------------------------------------ // alertUser // ------------------------------------ private void alertUser(UserPreferences userPref, ProcessedResults results) { // TODO: Create an app-specific reciever email address, so we can use that in the "sender" attribute // http://code.google.com/appengine/docs/java/mail/overview.html if (userPref.alertViaEmail) { mail.send sender: "[email protected]", to: "${userPref.owner}@gmail.com", subject: "GigBot Search Results", - htmlBody: "The GigBot found ${results.matchedListingCount} gigs based on your search preferences.<br/>http://thegigbot.appspot.com/gigs/list", + htmlBody: "The GigBot found ${results.matchedListingCount} gigs based on your search preferences.<br/>http://thegigbot.appspot.com/gigs/list" } } \ No newline at end of file
danker/gigbot
c43f12214ce235b70ad1ccf1c0bf64cd73d82392
Removed unused imports.
diff --git a/war/WEB-INF/groovy/listgigs.groovy b/war/WEB-INF/groovy/listgigs.groovy index 87ac7db..0c309ee 100644 --- a/war/WEB-INF/groovy/listgigs.groovy +++ b/war/WEB-INF/groovy/listgigs.groovy @@ -1,46 +1,43 @@ import com.breomedia.gigbot.GigProcessor import com.breomedia.gigbot.ProcessedResults import com.breomedia.gigbot.UserPreferences import com.breomedia.gigbot.dao.ProcessedResultsDAO import com.breomedia.gigbot.dao.UserPreferencesDAO -import com.google.appengine.api.datastore.* -import static com.google.appengine.api.datastore.FetchOptions.Builder.* - // get the prefs for the currently logged-in user UserPreferences userPrefs = new UserPreferencesDAO().getPreferencesForUser(user.nickname) def seeds = userPrefs.seeds.split(", ") request['seedstr'] = userPrefs.seeds def keywords = userPrefs.keywords.split(", ") request['keywordstr'] = userPrefs.keywords request['currentUser'] = user request['results'] = getResults(seeds, keywords) forward 'gigs.gtpl' // ------------------------------------ private ProcessedResults getResults(seeds, keywords) { // if we have results cached/saved, return those. // Otherwise fetch the latest and greatest ProcessedResultsDAO processedResultsDAO = new ProcessedResultsDAO() ProcessedResults results = processedResultsDAO.getResultsFromDatastore(user.nickname) if (!results) { log.info "Did not find results in the datastore for user = ${user.nickname}, fetching new results..." results = GigProcessor.process(user, seeds, keywords) processedResultsDAO.saveResults(results) } else { log.info "Found results (as of: ${results.lastRun} ) in the datastore for user = ${user.nickname}" } return results } \ No newline at end of file
danker/gigbot
49fc89327c8e263c18608f257ad1c8b1d93f6cfe
Adding email functionality for cron job.
diff --git a/war/WEB-INF/groovy/gigscron.groovy b/war/WEB-INF/groovy/gigscron.groovy index cc18e32..98dce3d 100644 --- a/war/WEB-INF/groovy/gigscron.groovy +++ b/war/WEB-INF/groovy/gigscron.groovy @@ -1,108 +1,117 @@ import com.breomedia.gigbot.GigProcessor import com.breomedia.gigbot.ProcessedResults import com.breomedia.gigbot.Listing import com.breomedia.gigbot.UserPreferences import com.breomedia.gigbot.dao.ProcessedResultsDAO import com.breomedia.gigbot.dao.UserPreferencesDAO import com.google.appengine.api.datastore.* import static com.google.appengine.api.datastore.FetchOptions.Builder.* // run each users job based on their preferences process(new UserPreferencesDAO().getUserPreferences()) // ------------------------------------ // process // ------------------------------------ private void process(List userPrefs) { ProcessedResultsDAO processedResultsDAO = new ProcessedResultsDAO() userPrefs.each { userPref -> // get the latest Processed Results, if any ProcessedResults oldResults = processedResultsDAO.getResultsFromDatastore(userPref.owner) // determine if we should process gigs, based on last run and user preference if (shouldProcess(userPref, oldResults)) { // delete old results and listings (TODO: Should we ever hold on to old listings?) deleteResultsAndListings(userPref.owner) // run new job and save results newProcessedResults = findNewGigsForUser(processedResultsDAO, userPref) // alert via email or gtalk alertUser(userPref, newProcessedResults) } } } // ------------------------------------ // shouldProcess // ------------------------------------ private boolean shouldProcess(UserPreferences userPrefs, ProcessedResults processedResults) { Date now = new Date() boolean shouldProcess = false use (groovy.time.TimeCategory) { if (userPrefs.runInterval && (now > (userPrefs.runInterval.hours + processedResults.lastRun))) { shouldProcess = true } } return shouldProcess } // ------------------------------------ // deleteResultsAndListings // ------------------------------------ private void deleteResultsAndListings(String user) { //TODO: Get this code out of here into a DAO // delete the ProcessedResults entity datastore.withTransaction { def query = new Query("ProcessedResults") query.addFilter("owner", Query.FilterOperator.EQUAL, user) PreparedQuery preparedQuery = datastore.prepare(query) preparedQuery?.asSingleEntity()?.delete() } // delete the Listings def query = new Query("Listing") query.addFilter("owner", Query.FilterOperator.EQUAL, user) PreparedQuery preparedQuery = datastore.prepare(query) preparedQuery = datastore.prepare(query) // get all listings for the user and add to the ProcessedResults object // TODO: Deal with more than 1000 result gracefully preparedQuery?.asList(withLimit(1000)).each { listing -> listing.delete() } } // ------------------------------------ // findNewGigsForUser // ------------------------------------ private ProcessedResults findNewGigsForUser(ProcessedResultsDAO processedResultsDAO, UserPreferences userPref) { ProcessedResults newProcessedResults = null if (userPref.seeds && userPref.keywords) { newProcessedResults = GigProcessor.process(userPref.owner, userPref.seeds.split(", "), userPref.keywords.split(", ")) processedResultsDAO.saveResults(newProcessedResults) } else { log.info("User ${userPref.owner} does not have seed URLs or Search Terms (Keywords) specified."); } return newProcessedResults } // ------------------------------------ // alertUser // ------------------------------------ private void alertUser(UserPreferences userPref, ProcessedResults results) { - // TODO: Implement email and IM alerting + + // TODO: Create an app-specific reciever email address, so we can use that in the "sender" attribute + // http://code.google.com/appengine/docs/java/mail/overview.html + if (userPref.alertViaEmail) { + mail.send sender: "[email protected]", + to: "${userPref.owner}@gmail.com", + subject: "GigBot Search Results", + htmlBody: "The GigBot found ${results.matchedListingCount} gigs based on your search preferences.<br/>http://thegigbot.appspot.com/gigs/list", + } + } \ No newline at end of file
danker/gigbot
be5cc521d23a2c0e9f29cf7714984f8aecbbe8cd
Refactor of UserPreferences management.
diff --git a/src/com/breomedia/gigbot/dao/UserPreferencesDAO.groovy b/src/com/breomedia/gigbot/dao/UserPreferencesDAO.groovy index 752c17e..4ec8e7b 100644 --- a/src/com/breomedia/gigbot/dao/UserPreferencesDAO.groovy +++ b/src/com/breomedia/gigbot/dao/UserPreferencesDAO.groovy @@ -1,68 +1,76 @@ package com.breomedia.gigbot.dao import com.breomedia.gigbot.UserPreferences import groovyx.gaelyk.logging.GroovyLogger import com.google.appengine.api.datastore.* import static com.google.appengine.api.datastore.FetchOptions.Builder.* class UserPreferencesDAO { // ------------------------------------ // getUserPreferences // ------------------------------------ public List getUserPreferences(limit=1000) { // TODO: Gracefully handle more than a thousand users List userPrefs = new ArrayList() def query = new Query("UserPreferences") PreparedQuery preparedQuery = DatastoreServiceFactory.datastoreService.prepare(query) preparedQuery.asList(withLimit(limit)).each { upEntity -> userPrefs.add(getUserPreferencesObjectFromEntity(upEntity)) //TODO: wish I could do it this way! //userPrefs.add(it as UserPreferences) } return userPrefs } // ------------------------------------ // getPreferencesForUser // ------------------------------------ public UserPreferences getPreferencesForUser(user) { + return getUserPreferencesObjectFromEntity(getPreferencesEntityForUser(user)) + } + + // ------------------------------------ + // getPreferencesEntityForUser + // ------------------------------------ + public def getPreferencesEntityForUser(user) { def query = new Query("UserPreferences") query.addFilter("owner", Query.FilterOperator.EQUAL, user) PreparedQuery preparedQuery = DatastoreServiceFactory.datastoreService.prepare(query) - def upEntity = preparedQuery.asSingleEntity() - - return getUserPreferencesObjectFromEntity(upEntity) + return preparedQuery?.asSingleEntity() + } // ------------------------------------ // getUserPreferencesObjectFromEntity // ------------------------------------ private UserPreferences getUserPreferencesObjectFromEntity(upEntity) { + // TODO: Figure out why "up = upEntity as UserPreferences" barfs on non-string values when the value from the Entity is null. + // NOTE: the above would only work in a groovlet...but I still can't get it to work regardless UserPreferences up = new UserPreferences() if (upEntity.runInterval) { up.runInterval = upEntity.runInterval as Integer } if (upEntity.alertViaEmail) { up.alertViaEmail = true } if (upEntity.alertViaGTalk) { up.alertViaGTalk = true } up.seeds = upEntity.seeds up.keywords = upEntity.keywords up.owner = upEntity.owner return up } } \ No newline at end of file diff --git a/war/WEB-INF/groovy/getuserprefs.groovy b/war/WEB-INF/groovy/getuserprefs.groovy index d9caefa..d11abc2 100644 --- a/war/WEB-INF/groovy/getuserprefs.groovy +++ b/war/WEB-INF/groovy/getuserprefs.groovy @@ -1,31 +1,13 @@ import com.breomedia.gigbot.UserPreferences -import com.google.appengine.api.datastore.* +import com.breomedia.gigbot.dao.UserPreferencesDAO -def query = new Query("UserPreferences") -query.addFilter("owner", Query.FilterOperator.EQUAL, user.nickname) -PreparedQuery preparedQuery = datastore.prepare(query) +UserPreferencesDAO upDAO = new UserPreferencesDAO() -Entity upEntity = preparedQuery.asSingleEntity() - -UserPreferences up = new UserPreferences() -if (upEntity) { - // TODO: Figure out why "up = upEntity as UserPreferences" barfs on non-string values when the value from the Entity is null. - // TODO: Possibly move this to a UserPrefs DAO because we're converting from an Entity to POGO here and in gigscron.groovy - if (upEntity.runInterval) { - up.runInterval = upEntity.runInterval as Integer - } - if (upEntity.alertViaEmail) { - up.alertViaEmail = true - } - if (upEntity.alertViaGTalk) { - up.alertViaGTalk = true - } - up.seeds = upEntity.seeds - up.keywords = upEntity.keywords -} +UserPreferences up = upDAO.getPreferencesForUser(user.nickname) +def upEntity = upDAO.getPreferencesEntityForUser(user.nickname) request.currentUser = user request.upKey = upEntity?.key request.userPrefs = up forward 'edituserprefs.gtpl' \ No newline at end of file diff --git a/war/WEB-INF/groovy/gigscron.groovy b/war/WEB-INF/groovy/gigscron.groovy index 6e85608..cc18e32 100644 --- a/war/WEB-INF/groovy/gigscron.groovy +++ b/war/WEB-INF/groovy/gigscron.groovy @@ -1,143 +1,108 @@ import com.breomedia.gigbot.GigProcessor import com.breomedia.gigbot.ProcessedResults import com.breomedia.gigbot.Listing import com.breomedia.gigbot.UserPreferences import com.breomedia.gigbot.dao.ProcessedResultsDAO +import com.breomedia.gigbot.dao.UserPreferencesDAO import com.google.appengine.api.datastore.* import static com.google.appengine.api.datastore.FetchOptions.Builder.* // run each users job based on their preferences -process(getUserPreferences()) - -// ------------------------------------ -// getUserPreferences -// ------------------------------------ -private List getUserPreferences() { - - List userPrefs = new ArrayList() - - def query = new Query("UserPreferences") - PreparedQuery preparedQuery = datastore.prepare(query) - // TODO: Gracefully handle more than a thousand users - preparedQuery.asList(withLimit(1000)).each { upEntity -> - - UserPreferences up = new UserPreferences() - - if (upEntity.runInterval) { - up.runInterval = upEntity.runInterval as Integer - } - if (upEntity.alertViaEmail) { - up.alertViaEmail = true - } - if (upEntity.alertViaGTalk) { - up.alertViaGTalk = true - } - up.seeds = upEntity.seeds - up.keywords = upEntity.keywords - up.owner = upEntity.owner - - userPrefs.add(up) - //TODO: MOVE THIS TO A DAO!!! - //TODO: wish I could do it this way! - //userPrefs.add(it as UserPreferences) - } - - return userPrefs -} +process(new UserPreferencesDAO().getUserPreferences()) // ------------------------------------ // process // ------------------------------------ private void process(List userPrefs) { ProcessedResultsDAO processedResultsDAO = new ProcessedResultsDAO() userPrefs.each { userPref -> // get the latest Processed Results, if any ProcessedResults oldResults = processedResultsDAO.getResultsFromDatastore(userPref.owner) // determine if we should process gigs, based on last run and user preference if (shouldProcess(userPref, oldResults)) { // delete old results and listings (TODO: Should we ever hold on to old listings?) deleteResultsAndListings(userPref.owner) // run new job and save results newProcessedResults = findNewGigsForUser(processedResultsDAO, userPref) // alert via email or gtalk alertUser(userPref, newProcessedResults) } } } // ------------------------------------ // shouldProcess // ------------------------------------ private boolean shouldProcess(UserPreferences userPrefs, ProcessedResults processedResults) { Date now = new Date() boolean shouldProcess = false use (groovy.time.TimeCategory) { - if (now > (userPrefs.runInterval.hours + processedResults.lastRun)) { + if (userPrefs.runInterval && (now > (userPrefs.runInterval.hours + processedResults.lastRun))) { shouldProcess = true } } return shouldProcess } // ------------------------------------ // deleteResultsAndListings // ------------------------------------ -private void deleteResultsAndListings(String user) { +private void deleteResultsAndListings(String user) { //TODO: Get this code out of here into a DAO // delete the ProcessedResults entity datastore.withTransaction { def query = new Query("ProcessedResults") query.addFilter("owner", Query.FilterOperator.EQUAL, user) PreparedQuery preparedQuery = datastore.prepare(query) preparedQuery?.asSingleEntity()?.delete() } // delete the Listings def query = new Query("Listing") query.addFilter("owner", Query.FilterOperator.EQUAL, user) PreparedQuery preparedQuery = datastore.prepare(query) preparedQuery = datastore.prepare(query) // get all listings for the user and add to the ProcessedResults object // TODO: Deal with more than 1000 result gracefully preparedQuery?.asList(withLimit(1000)).each { listing -> listing.delete() } } // ------------------------------------ // findNewGigsForUser // ------------------------------------ private ProcessedResults findNewGigsForUser(ProcessedResultsDAO processedResultsDAO, UserPreferences userPref) { ProcessedResults newProcessedResults = null if (userPref.seeds && userPref.keywords) { newProcessedResults = GigProcessor.process(userPref.owner, userPref.seeds.split(", "), userPref.keywords.split(", ")) processedResultsDAO.saveResults(newProcessedResults) } else { log.info("User ${userPref.owner} does not have seed URLs or Search Terms (Keywords) specified."); } return newProcessedResults } // ------------------------------------ // alertUser // ------------------------------------ private void alertUser(UserPreferences userPref, ProcessedResults results) { // TODO: Implement email and IM alerting } \ No newline at end of file diff --git a/war/WEB-INF/groovy/listgigs.groovy b/war/WEB-INF/groovy/listgigs.groovy index 81e8068..87ac7db 100644 --- a/war/WEB-INF/groovy/listgigs.groovy +++ b/war/WEB-INF/groovy/listgigs.groovy @@ -1,48 +1,46 @@ import com.breomedia.gigbot.GigProcessor import com.breomedia.gigbot.ProcessedResults import com.breomedia.gigbot.UserPreferences import com.breomedia.gigbot.dao.ProcessedResultsDAO import com.breomedia.gigbot.dao.UserPreferencesDAO import com.google.appengine.api.datastore.* import static com.google.appengine.api.datastore.FetchOptions.Builder.* // get the prefs for the currently logged-in user UserPreferences userPrefs = new UserPreferencesDAO().getPreferencesForUser(user.nickname) def seeds = userPrefs.seeds.split(", ") request['seedstr'] = userPrefs.seeds def keywords = userPrefs.keywords.split(", ") request['keywordstr'] = userPrefs.keywords -// grab the user request['currentUser'] = user - request['results'] = getResults(seeds, keywords) forward 'gigs.gtpl' // ------------------------------------ private ProcessedResults getResults(seeds, keywords) { // if we have results cached/saved, return those. // Otherwise fetch the latest and greatest ProcessedResultsDAO processedResultsDAO = new ProcessedResultsDAO() ProcessedResults results = processedResultsDAO.getResultsFromDatastore(user.nickname) if (!results) { log.info "Did not find results in the datastore for user = ${user.nickname}, fetching new results..." results = GigProcessor.process(user, seeds, keywords) processedResultsDAO.saveResults(results) } else { log.info "Found results (as of: ${results.lastRun} ) in the datastore for user = ${user.nickname}" } return results } \ No newline at end of file diff --git a/war/WEB-INF/routes.groovy b/war/WEB-INF/routes.groovy index 88440a8..79a42d8 100644 --- a/war/WEB-INF/routes.groovy +++ b/war/WEB-INF/routes.groovy @@ -1,12 +1,12 @@ // example routes /* get "/blog/@year/@month/@day/@title", forward: "/WEB-INF/groovy/blog.groovy?year=@year&month=@month&day=@day&title=@title" get "/something", redirect: "/blog/2008/10/20/something", cache: 2.hours get "/book/isbn/@isbn", forward: "/WEB-INF/groovy/book.groovy?isbn=@isbn", validate: { isbn ==~ /\d{9}(\d|X)/ } */ get "/hello", forward: "/hello.gtpl" get "/gigs/list", forward: "/listgigs.groovy" get "/gigs/userprefs", forward: "/getuserprefs.groovy" -get "/gigs/userprefsupdate", forward: "/saveuserprefs.groovy" +post "/gigs/userprefsupdate", forward: "/saveuserprefs.groovy" get "/cron/findgigs", forward: "/gigscron.groovy" \ No newline at end of file diff --git a/war/edituserprefs.gtpl b/war/edituserprefs.gtpl index a2c16c8..89c77f9 100644 --- a/war/edituserprefs.gtpl +++ b/war/edituserprefs.gtpl @@ -1,44 +1,44 @@ <% import com.breomedia.gigbot.UserPreferences %> <% include '/WEB-INF/includes/header.gtpl' %> <h2>Edit User Prefs for ${request.currentUser.nickname}</h2> -<form action="/gigs/userprefsupdate" method="GET"> +<form action="/gigs/userprefsupdate" method="POST"> <input type="hidden" name="id" value="${request.upKey?.id ?: ""}" /> <div> <p><label for="seeds">RSS Feeds: (comma-separated)</label></p> <textarea name="seeds" rows="10" cols="50">${request.userPrefs?.seeds ?: ""}</textarea> </div> <div> <p><label for="keywords">Keywords: (comma-separated)</label></p> <textarea name="keywords" rows="10" cols="50">${request.userPrefs?.keywords ?: ""}</textarea> </div> <div> <label for="alertViaEmail">Alert via Email?</label> <input type=checkbox name="alertViaEmail" value="true" ${!(request.userPrefs?.alertViaEmail) ?: "checked"} /> </div> <div> <label for="alertViaGTalk">Alert via GTalk?</label> <input type=checkbox name="alertViaGTalk" value="true" ${!(request.userPrefs?.alertViaGTalk) ?: "checked"} /> </div> <div> <p><label for="runInterval">How often would you like to check for new gigs?</label></p> Once daily: <input type="radio" name="runInterval" value="24" ${!(request.userPrefs?.runInterval == 24) ?: "checked"} /><br/> Twice daily: <input type="radio" name="runInterval" value="12" ${!(request.userPrefs?.runInterval == 12) ?: "checked"} /><br/> Four times daily: <input type="radio" name="runInterval" value="6" ${!(request.userPrefs?.runInterval == 6) ?: "checked"} /> </div> <div> <p><input type="submit" value="Save Preferences"></p> </div> </form> <% include '/WEB-INF/includes/footer.gtpl' %> diff --git a/war/index.gtpl b/war/index.gtpl index 15507c0..60d7b43 100644 --- a/war/index.gtpl +++ b/war/index.gtpl @@ -1,18 +1,21 @@ <% include '/WEB-INF/includes/header.gtpl' %> <h1>Welcome</h1> <p> - What <a href="datetime.groovy">time</a> is it? + <% if (user && users.isUserAdmin()) { %> + You're an Admin!<br> + What <a href="datetime.groovy">time</a> is it? + <% } %> </p> <% if (users.isUserLoggedIn()) { %> <a href="/gigs/userprefs">Manage Preferences</a> | <a href="/gigs/list">View gigs</a> | <a href="${users.createLogoutURL('/')}">Logout</a> <% } else { %> <a href="${users.createLoginURL('/')}">Login</a> <% } %> <% include '/WEB-INF/includes/footer.gtpl' %>
danker/gigbot
f4f47e5e8fb81e01f05c65d511e069614bafb197
More cleanup.
diff --git a/war/WEB-INF/groovy/listgigs.groovy b/war/WEB-INF/groovy/listgigs.groovy index 95e9774..81e8068 100644 --- a/war/WEB-INF/groovy/listgigs.groovy +++ b/war/WEB-INF/groovy/listgigs.groovy @@ -1,49 +1,48 @@ import com.breomedia.gigbot.GigProcessor import com.breomedia.gigbot.ProcessedResults import com.breomedia.gigbot.UserPreferences import com.breomedia.gigbot.dao.ProcessedResultsDAO import com.breomedia.gigbot.dao.UserPreferencesDAO import com.google.appengine.api.datastore.* import static com.google.appengine.api.datastore.FetchOptions.Builder.* // get the prefs for the currently logged-in user UserPreferences userPrefs = new UserPreferencesDAO().getPreferencesForUser(user.nickname) def seeds = userPrefs.seeds.split(", ") request['seedstr'] = userPrefs.seeds def keywords = userPrefs.keywords.split(", ") request['keywordstr'] = userPrefs.keywords // grab the user request['currentUser'] = user -log.info "user object ${user}" request['results'] = getResults(seeds, keywords) forward 'gigs.gtpl' // ------------------------------------ private ProcessedResults getResults(seeds, keywords) { // if we have results cached/saved, return those. // Otherwise fetch the latest and greatest ProcessedResultsDAO processedResultsDAO = new ProcessedResultsDAO() ProcessedResults results = processedResultsDAO.getResultsFromDatastore(user.nickname) if (!results) { log.info "Did not find results in the datastore for user = ${user.nickname}, fetching new results..." results = GigProcessor.process(user, seeds, keywords) processedResultsDAO.saveResults(results) } else { log.info "Found results (as of: ${results.lastRun} ) in the datastore for user = ${user.nickname}" } return results } \ No newline at end of file diff --git a/war/WEB-INF/routes.groovy b/war/WEB-INF/routes.groovy index 0a433db..88440a8 100644 --- a/war/WEB-INF/routes.groovy +++ b/war/WEB-INF/routes.groovy @@ -1,13 +1,12 @@ // example routes /* get "/blog/@year/@month/@day/@title", forward: "/WEB-INF/groovy/blog.groovy?year=@year&month=@month&day=@day&title=@title" get "/something", redirect: "/blog/2008/10/20/something", cache: 2.hours get "/book/isbn/@isbn", forward: "/WEB-INF/groovy/book.groovy?isbn=@isbn", validate: { isbn ==~ /\d{9}(\d|X)/ } */ get "/hello", forward: "/hello.gtpl" get "/gigs/list", forward: "/listgigs.groovy" -//get "/gigs/search", forward: "/gigsearchform.gtpl" get "/gigs/userprefs", forward: "/getuserprefs.groovy" get "/gigs/userprefsupdate", forward: "/saveuserprefs.groovy" get "/cron/findgigs", forward: "/gigscron.groovy" \ No newline at end of file diff --git a/war/gigs.gtpl b/war/gigs.gtpl index 7c10c2b..49a480d 100644 --- a/war/gigs.gtpl +++ b/war/gigs.gtpl @@ -1,17 +1,17 @@ <% import com.breomedia.gigbot.ProcessedResults %> <% import com.breomedia.gigbot.Listing %> <html> <body> <p>Welcome, ${request.currentUser.nickname} <p>RSS Feeds Scanned: ${request.seedstr}</p> <p>Keywords: ${request.keywordstr}</p> - <h1>${request.results.matchedListingCount} Matchings Gigs as of: ${request.results.lastRun.format("EEE, d MMM yyyy HH:mm:ss z")}</h1> + <h1>${request.results.matchedListingCount} Matchings Gigs as of: ${request.results.lastRun.format("EEE, d MMM yyyy HH:mm:ss zzz")}</h1> <ul> <% request.results.matchedListings.each { %> <li><a href="${it.link}">${it.title}</a></li> <% } %> </ul> </body> </html> \ No newline at end of file
danker/gigbot
4bd93e2874d0c888a2df63e19c3d7865fe342ba8
Cron job working, removing original search form.
diff --git a/src/com/breomedia/gigbot/GigProcessor.groovy b/src/com/breomedia/gigbot/GigProcessor.groovy index 8b58bc7..2ecaa0d 100644 --- a/src/com/breomedia/gigbot/GigProcessor.groovy +++ b/src/com/breomedia/gigbot/GigProcessor.groovy @@ -1,70 +1,68 @@ package com.breomedia.gigbot import groovyx.gaelyk.logging.GroovyLogger import com.google.appengine.api.users.User class GigProcessor { static def log = new GroovyLogger("GigProcessor") static ProcessedResults process(user, seeds, keywords) { - ProcessedResults results = new ProcessedResults(owner: user.nickname) + ProcessedResults results = new ProcessedResults(owner: user) def slurper = new XmlSlurper() // Now let's loop through each seed URL in turn. seeds.each() { log.info "Accessing seed URL ${it}" def seedURL = new URL(it) seedURL.withReader { seedReader -> def rss = slurper.parse(seedReader) // need to get at some specific namespaces def ns = [:] ns.dc = "http://purl.org/dc/elements/1.1/" ns.rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns" rss.declareNamespace(ns) log.info "JOBS FROM CHANNEL: " + rss.channel.'dc:title' log.info "CHANNEL LINK: " + rss.channel.link // case-insensitive, match the pattern anywhere in the body of the input string def myRegex = /(?im)^.*\b(/ + keywords.join("|") + /)\b.*$/ log.info "REGEX to match: ${myRegex}" log.info "Matching description against the following words: " + keywords.join(" OR ") def matchedListings = 0 rss.item.each { String description = it.description.text() if (description.find(myRegex)) { results.matchedListings.add(new Listing(title: it.'dc:title', link: it.link)) //log.info "=#" * 12 + " MATCH ${matchedListings+1} " + "=#" * 12 //log.info "JOB TITLE: " + it.'dc:title' //log.info "JOB LINK: " + it.link //log.info "JOB DESCRIPTION\n" + description matchedListings++ } } results.matchedListingCount = matchedListings results.totalItemsProcessed = rss.item.size() log.info "Matched ${matchedListings} of ${rss.item.size()} listings." } } - //GigProcessor.saveResults(results) - return results } } \ No newline at end of file diff --git a/src/com/breomedia/gigbot/ProcessedResults.groovy b/src/com/breomedia/gigbot/ProcessedResults.groovy index 2ffefea..09260ac 100644 --- a/src/com/breomedia/gigbot/ProcessedResults.groovy +++ b/src/com/breomedia/gigbot/ProcessedResults.groovy @@ -1,13 +1,16 @@ package com.breomedia.gigbot class ProcessedResults { String owner List matchedListings = [ ] Date lastRun = new Date() // stats Long totalItemsProcessed Long matchedListingCount + String toString() { + "owner: $owner, lastRun: $lastRun, totalItemsProcessed: $totalItemsProcessed, matchedListingCount: $matchedListingCount, matchedListings: $matchedListings" + } } \ No newline at end of file diff --git a/src/com/breomedia/gigbot/dao/ProcessedResultsDAO.groovy b/src/com/breomedia/gigbot/dao/ProcessedResultsDAO.groovy new file mode 100644 index 0000000..a203b42 --- /dev/null +++ b/src/com/breomedia/gigbot/dao/ProcessedResultsDAO.groovy @@ -0,0 +1,96 @@ +package com.breomedia.gigbot.dao + +import com.breomedia.gigbot.ProcessedResults +import com.breomedia.gigbot.Listing + +import groovyx.gaelyk.logging.GroovyLogger +import com.google.appengine.api.datastore.* +import static com.google.appengine.api.datastore.FetchOptions.Builder.* + +class ProcessedResultsDAO { + + def log = new GroovyLogger("ProcessedResultsDAO") + + // ------------------------------------ + // getResultsFromDatastore + // ------------------------------------ + public ProcessedResults getResultsFromDatastore(String owner) { + + ProcessedResults results = null + + def query = new Query("ProcessedResults") + query.addFilter("owner", Query.FilterOperator.EQUAL, owner) + PreparedQuery preparedQuery = DatastoreServiceFactory.datastoreService.prepare(query) + def resultEntity = preparedQuery.asSingleEntity() + + if (resultEntity) { + + // something was returned, so grab all the listings too and + // construct the ProcessedResults object + //TODO: WHY DOESN'T THIS WORK? results = resultEntity as ProcessedResults + results = getProcessedResultsFromEntity(resultEntity) + + query = new Query("Listing") + query.addFilter("owner", Query.FilterOperator.EQUAL, owner) + preparedQuery = DatastoreServiceFactory.datastoreService.prepare(query) + // get all listings for the logged in user and add to the + // ProcessedResults object + preparedQuery.asList(withLimit(1000)).each { + results.matchedListings.add(new Listing(title: it.title, link: it.link)) + } + + } else { + log.info "No existing processed results for user: ${owner}" + } + + return results + } + + // ------------------------------------ + // saveResults + // ------------------------------------ + public void saveResults(results) { + + Entity resultsEntity = new Entity("ProcessedResults") + + resultsEntity.matchedListingCount = results.matchedListingCount + resultsEntity.totalItemsProcessed = results.totalItemsProcessed + resultsEntity.owner = results.owner + resultsEntity.lastRun = results.lastRun + resultsEntity.save() + + results.matchedListings.each { + Entity listing = it as Entity + listing.owner = results.owner + //TODO: It would be much more awesome to use the mixed-in save method! -- listing.save() + DatastoreServiceFactory.datastoreService.put(listing) + } + + } + + // ------------------------------------ + // getProcessedResultsFromEntity + // ------------------------------------ + private ProcessedResults getProcessedResultsFromEntity(prEntity) { + + ProcessedResults pr = new ProcessedResults() + + pr.owner = prEntity.owner + + if (prEntity.lastRun) { + pr.lastRun = prEntity.lastRun as Date + } + + if (prEntity.totalItemsProcessed) { + pr.totalItemsProcessed = prEntity.totalItemsProcessed as Long + } + + if (prEntity.matchedListingCount) { + pr.matchedListingCount = prEntity.matchedListingCount as Long + } + + return pr + } + + //TODO: Need to move the delete method here, but would like to inject the "datastore" ref in this object +} \ No newline at end of file diff --git a/src/com/breomedia/gigbot/dao/UserPreferencesDAO.groovy b/src/com/breomedia/gigbot/dao/UserPreferencesDAO.groovy new file mode 100644 index 0000000..752c17e --- /dev/null +++ b/src/com/breomedia/gigbot/dao/UserPreferencesDAO.groovy @@ -0,0 +1,68 @@ +package com.breomedia.gigbot.dao + +import com.breomedia.gigbot.UserPreferences + +import groovyx.gaelyk.logging.GroovyLogger +import com.google.appengine.api.datastore.* +import static com.google.appengine.api.datastore.FetchOptions.Builder.* + +class UserPreferencesDAO { + + // ------------------------------------ + // getUserPreferences + // ------------------------------------ + public List getUserPreferences(limit=1000) { // TODO: Gracefully handle more than a thousand users + + List userPrefs = new ArrayList() + + def query = new Query("UserPreferences") + PreparedQuery preparedQuery = DatastoreServiceFactory.datastoreService.prepare(query) + preparedQuery.asList(withLimit(limit)).each { upEntity -> + + userPrefs.add(getUserPreferencesObjectFromEntity(upEntity)) + //TODO: wish I could do it this way! + //userPrefs.add(it as UserPreferences) + + } + + return userPrefs + } + + // ------------------------------------ + // getPreferencesForUser + // ------------------------------------ + public UserPreferences getPreferencesForUser(user) { + + def query = new Query("UserPreferences") + query.addFilter("owner", Query.FilterOperator.EQUAL, user) + PreparedQuery preparedQuery = DatastoreServiceFactory.datastoreService.prepare(query) + def upEntity = preparedQuery.asSingleEntity() + + return getUserPreferencesObjectFromEntity(upEntity) + + } + + // ------------------------------------ + // getUserPreferencesObjectFromEntity + // ------------------------------------ + private UserPreferences getUserPreferencesObjectFromEntity(upEntity) { + + UserPreferences up = new UserPreferences() + + if (upEntity.runInterval) { + up.runInterval = upEntity.runInterval as Integer + } + if (upEntity.alertViaEmail) { + up.alertViaEmail = true + } + if (upEntity.alertViaGTalk) { + up.alertViaGTalk = true + } + up.seeds = upEntity.seeds + up.keywords = upEntity.keywords + up.owner = upEntity.owner + + return up + } + +} \ No newline at end of file diff --git a/war/WEB-INF/groovy/getuserprefs.groovy b/war/WEB-INF/groovy/getuserprefs.groovy index a4ca054..d9caefa 100644 --- a/war/WEB-INF/groovy/getuserprefs.groovy +++ b/war/WEB-INF/groovy/getuserprefs.groovy @@ -1,30 +1,31 @@ import com.breomedia.gigbot.UserPreferences import com.google.appengine.api.datastore.* def query = new Query("UserPreferences") query.addFilter("owner", Query.FilterOperator.EQUAL, user.nickname) PreparedQuery preparedQuery = datastore.prepare(query) Entity upEntity = preparedQuery.asSingleEntity() UserPreferences up = new UserPreferences() if (upEntity) { // TODO: Figure out why "up = upEntity as UserPreferences" barfs on non-string values when the value from the Entity is null. + // TODO: Possibly move this to a UserPrefs DAO because we're converting from an Entity to POGO here and in gigscron.groovy if (upEntity.runInterval) { up.runInterval = upEntity.runInterval as Integer } if (upEntity.alertViaEmail) { up.alertViaEmail = true } if (upEntity.alertViaGTalk) { up.alertViaGTalk = true } up.seeds = upEntity.seeds up.keywords = upEntity.keywords } request.currentUser = user request.upKey = upEntity?.key request.userPrefs = up forward 'edituserprefs.gtpl' \ No newline at end of file diff --git a/war/WEB-INF/groovy/gigscron.groovy b/war/WEB-INF/groovy/gigscron.groovy index 9b8c404..6e85608 100644 --- a/war/WEB-INF/groovy/gigscron.groovy +++ b/war/WEB-INF/groovy/gigscron.groovy @@ -1,161 +1,143 @@ import com.breomedia.gigbot.GigProcessor import com.breomedia.gigbot.ProcessedResults import com.breomedia.gigbot.Listing import com.breomedia.gigbot.UserPreferences +import com.breomedia.gigbot.dao.ProcessedResultsDAO import com.google.appengine.api.datastore.* import static com.google.appengine.api.datastore.FetchOptions.Builder.* // run each users job based on their preferences process(getUserPreferences()) // ------------------------------------ // getUserPreferences // ------------------------------------ private List getUserPreferences() { - List userPrefs = null + List userPrefs = new ArrayList() def query = new Query("UserPreferences") PreparedQuery preparedQuery = datastore.prepare(query) // TODO: Gracefully handle more than a thousand users - preparedQuery.asList(withLimit(1000)).each { - userPrefs.add(it as UserPreferences) + preparedQuery.asList(withLimit(1000)).each { upEntity -> + + UserPreferences up = new UserPreferences() + + if (upEntity.runInterval) { + up.runInterval = upEntity.runInterval as Integer + } + if (upEntity.alertViaEmail) { + up.alertViaEmail = true + } + if (upEntity.alertViaGTalk) { + up.alertViaGTalk = true + } + up.seeds = upEntity.seeds + up.keywords = upEntity.keywords + up.owner = upEntity.owner + + userPrefs.add(up) + //TODO: MOVE THIS TO A DAO!!! + //TODO: wish I could do it this way! + //userPrefs.add(it as UserPreferences) } return userPrefs } // ------------------------------------ // process // ------------------------------------ private void process(List userPrefs) { + ProcessedResultsDAO processedResultsDAO = new ProcessedResultsDAO() + userPrefs.each { userPref -> - + // get the latest Processed Results, if any - ProcessedResults oldResults = getResultsFromDatastore() //TODO: Refactor...using this method in 2 diff groovlets! + ProcessedResults oldResults = processedResultsDAO.getResultsFromDatastore(userPref.owner) // determine if we should process gigs, based on last run and user preference if (shouldProcess(userPref, oldResults)) { - // delete old results and listings + // delete old results and listings (TODO: Should we ever hold on to old listings?) deleteResultsAndListings(userPref.owner) // run new job and save results - ProcessedResults newProcessedResults = GigProcessor.process(userPref.owner, userPref.seeds, userPref.keywords) - saveResults(newProcessedResults) //TODO: Refactor...using this method in 2 diff groovlets + newProcessedResults = findNewGigsForUser(processedResultsDAO, userPref) // alert via email or gtalk alertUser(userPref, newProcessedResults) } } } // ------------------------------------ // shouldProcess // ------------------------------------ private boolean shouldProcess(UserPreferences userPrefs, ProcessedResults processedResults) { Date now = new Date() boolean shouldProcess = false use (groovy.time.TimeCategory) { - if (now > ((24/userPrefs.runInterval).hours + processedResults.lastRun)) { + if (now > (userPrefs.runInterval.hours + processedResults.lastRun)) { shouldProcess = true } } return shouldProcess } // ------------------------------------ -// getResultsFromDatastore +// deleteResultsAndListings // ------------------------------------ -private ProcessedResults getResultsFromDatastore() { - - ProcessedResults results = null - - def query = new Query("ProcessedResults") - query.addFilter("owner", Query.FilterOperator.EQUAL, user.nickname) - PreparedQuery preparedQuery = datastore.prepare(query) - def resultEntity = preparedQuery.asSingleEntity() - - if (resultEntity) { +private void deleteResultsAndListings(String user) { - // something was returned, so grab all the listings too and - // construct the ProcessedResults object - results = resultEntity as ProcessedResults - - query = new Query("Listing") - query.addFilter("owner", Query.FilterOperator.EQUAL, user.nickname) - preparedQuery = datastore.prepare(query) - // get all listings for the logged in user and add to the - // ProcessedResults object - preparedQuery.asList(withLimit(1000)).each { - results.matchedListings.add(new Listing(title: it.title, link: it.link)) - } - + // delete the ProcessedResults entity + datastore.withTransaction { + def query = new Query("ProcessedResults") + query.addFilter("owner", Query.FilterOperator.EQUAL, user) + PreparedQuery preparedQuery = datastore.prepare(query) + preparedQuery?.asSingleEntity()?.delete() } - - return results -} - -// ------------------------------------ -// saveResults -// ------------------------------------ -private void saveResults(results) { - - Entity resultsEntity = new Entity("ProcessedResults") - - resultsEntity.matchedListingCount = results.matchedListingCount - resultsEntity.totalItemsProcessed = results.totalItemsProcessed - resultsEntity.owner = results.owner - resultsEntity.lastRun = results.lastRun - resultsEntity.save() - results.matchedListings.each { - Entity listing = it as Entity - listing.owner = results.owner - listing.save() + // delete the Listings + def query = new Query("Listing") + query.addFilter("owner", Query.FilterOperator.EQUAL, user) + PreparedQuery preparedQuery = datastore.prepare(query) + preparedQuery = datastore.prepare(query) + // get all listings for the user and add to the ProcessedResults object + // TODO: Deal with more than 1000 result gracefully + preparedQuery?.asList(withLimit(1000)).each { listing -> + listing.delete() } } // ------------------------------------ -// deleteResultsAndListings +// findNewGigsForUser // ------------------------------------ -private void deleteResultsAndListings(String user) { +private ProcessedResults findNewGigsForUser(ProcessedResultsDAO processedResultsDAO, UserPreferences userPref) { - // delete the ProcessedResults entity - datastore.withTransaction { - def query = new Query("ProcessedResults") - query.addFilter("owner", Query.FilterOperator.EQUAL, user) - PreparedQuery preparedQuery = datastore.prepare(query) - preparedQuery.asSingleEntity().delete() - } - - // delete the Listings - datastore.withTransaction { - def query = new Query("Listing") - query.addFilter("owner", Query.FilterOperator.EQUAL, user) - PreparedQuery preparedQuery = datastore.prepare(query) - preparedQuery = datastore.prepare(query) - // get all listings for the logged in user and add to the - // ProcessedResults object - // TODO: Deal with more than 1000 result gracefully - preparedQuery.asList(withLimit(1000)).each { listing -> - listing.delete() - } + ProcessedResults newProcessedResults = null + + if (userPref.seeds && userPref.keywords) { + newProcessedResults = GigProcessor.process(userPref.owner, userPref.seeds.split(", "), userPref.keywords.split(", ")) + processedResultsDAO.saveResults(newProcessedResults) + } else { + log.info("User ${userPref.owner} does not have seed URLs or Search Terms (Keywords) specified."); } + return newProcessedResults } // ------------------------------------ // alertUser // ------------------------------------ private void alertUser(UserPreferences userPref, ProcessedResults results) { // TODO: Implement email and IM alerting } \ No newline at end of file diff --git a/war/WEB-INF/groovy/listgigs.groovy b/war/WEB-INF/groovy/listgigs.groovy new file mode 100644 index 0000000..95e9774 --- /dev/null +++ b/war/WEB-INF/groovy/listgigs.groovy @@ -0,0 +1,49 @@ +import com.breomedia.gigbot.GigProcessor +import com.breomedia.gigbot.ProcessedResults +import com.breomedia.gigbot.UserPreferences +import com.breomedia.gigbot.dao.ProcessedResultsDAO +import com.breomedia.gigbot.dao.UserPreferencesDAO + +import com.google.appengine.api.datastore.* +import static com.google.appengine.api.datastore.FetchOptions.Builder.* + +// get the prefs for the currently logged-in user +UserPreferences userPrefs = new UserPreferencesDAO().getPreferencesForUser(user.nickname) + +def seeds = userPrefs.seeds.split(", ") +request['seedstr'] = userPrefs.seeds + +def keywords = userPrefs.keywords.split(", ") +request['keywordstr'] = userPrefs.keywords + +// grab the user +request['currentUser'] = user +log.info "user object ${user}" + +request['results'] = getResults(seeds, keywords) + +forward 'gigs.gtpl' + +// ------------------------------------ +private ProcessedResults getResults(seeds, keywords) { + + // if we have results cached/saved, return those. + // Otherwise fetch the latest and greatest + ProcessedResultsDAO processedResultsDAO = new ProcessedResultsDAO() + ProcessedResults results = processedResultsDAO.getResultsFromDatastore(user.nickname) + + if (!results) { + + log.info "Did not find results in the datastore for user = ${user.nickname}, fetching new results..." + + results = GigProcessor.process(user, seeds, keywords) + processedResultsDAO.saveResults(results) + + } else { + + log.info "Found results (as of: ${results.lastRun} ) in the datastore for user = ${user.nickname}" + + } + + return results +} \ No newline at end of file diff --git a/war/WEB-INF/groovy/processgigs.groovy b/war/WEB-INF/groovy/processgigs.groovy index 39d9f56..b17a3fe 100644 --- a/war/WEB-INF/groovy/processgigs.groovy +++ b/war/WEB-INF/groovy/processgigs.groovy @@ -1,98 +1,48 @@ import com.breomedia.gigbot.GigProcessor import com.breomedia.gigbot.ProcessedResults import com.breomedia.gigbot.Listing +import com.breomedia.gigbot.dao.ProcessedResultsDAO import com.google.appengine.api.datastore.* import static com.google.appengine.api.datastore.FetchOptions.Builder.* -// TODO: Sanatize inputs! +//TODO: REMOVE THIS GROOVLET (and possibly gigsearchform.gtpl) +// TODO: Sanatize inputs! def seeds = params.seeds.split(", ") request['seedstr'] = params.seeds def keywords = params.keywords.split(", ") request['keywordstr'] = params.keywords // grab the user request['currentUser'] = user log.info "user object ${user}" request['results'] = getResults(seeds, keywords) forward 'gigs.gtpl' // ------------------------------------ -// Result Processing Methods -// ------------------------------------ - -// private ProcessedResults getResults(seeds, keywords) { // if we have results cached/saved, return those. // Otherwise fetch the latest and greatest - ProcessedResults results = getResultsFromDatastore() + ProcessedResultsDAO processedResultsDAO = new ProcessedResultsDAO() + ProcessedResults results = processedResultsDAO.getResultsFromDatastore(user.nickname) if (!results) { log.info "Did not find results in the datastore for user = ${user.nickname}, fetching new results..." results = GigProcessor.process(user, seeds, keywords) - saveResults(results) + processedResultsDAO.saveResults(results) } else { log.info "Found results (as of: ${results.lastRun} ) in the datastore for user = ${user.nickname}" } return results -} - -// -private ProcessedResults getResultsFromDatastore() { - - ProcessedResults results = null - - def query = new Query("ProcessedResults") - query.addFilter("owner", Query.FilterOperator.EQUAL, user.nickname) - PreparedQuery preparedQuery = datastore.prepare(query) - def resultEntity = preparedQuery.asSingleEntity() - - if (resultEntity) { - - // something was returned, so grab all the listings too and - // construct the ProcessedResults object - results = resultEntity as ProcessedResults - - query = new Query("Listing") - query.addFilter("owner", Query.FilterOperator.EQUAL, user.nickname) - preparedQuery = datastore.prepare(query) - // get all listings for the logged in user and add to the - // ProcessedResults object - preparedQuery.asList(withLimit(1000)).each { - results.matchedListings.add(new Listing(title: it.title, link: it.link)) - } - - } - - return results -} - -// -private void saveResults(results) { - - Entity resultsEntity = new Entity("ProcessedResults") - - resultsEntity.matchedListingCount = results.matchedListingCount - resultsEntity.totalItemsProcessed = results.totalItemsProcessed - resultsEntity.owner = results.owner - resultsEntity.lastRun = results.lastRun - resultsEntity.save() - - results.matchedListings.each { - Entity listing = it as Entity - listing.owner = results.owner - listing.save() - } - } \ No newline at end of file diff --git a/war/WEB-INF/routes.groovy b/war/WEB-INF/routes.groovy index cf4be9c..0a433db 100644 --- a/war/WEB-INF/routes.groovy +++ b/war/WEB-INF/routes.groovy @@ -1,13 +1,13 @@ // example routes /* get "/blog/@year/@month/@day/@title", forward: "/WEB-INF/groovy/blog.groovy?year=@year&month=@month&day=@day&title=@title" get "/something", redirect: "/blog/2008/10/20/something", cache: 2.hours get "/book/isbn/@isbn", forward: "/WEB-INF/groovy/book.groovy?isbn=@isbn", validate: { isbn ==~ /\d{9}(\d|X)/ } */ get "/hello", forward: "/hello.gtpl" -get "/gigs/list", forward: "/processgigs.groovy" -get "/gigs/search", forward: "/gigsearchform.gtpl" +get "/gigs/list", forward: "/listgigs.groovy" +//get "/gigs/search", forward: "/gigsearchform.gtpl" get "/gigs/userprefs", forward: "/getuserprefs.groovy" get "/gigs/userprefsupdate", forward: "/saveuserprefs.groovy" -//get "/cron/findgigs", forward: "/gigscron.groovy" \ No newline at end of file +get "/cron/findgigs", forward: "/gigscron.groovy" \ No newline at end of file diff --git a/war/edituserprefs.gtpl b/war/edituserprefs.gtpl index 28ae5ef..a2c16c8 100644 --- a/war/edituserprefs.gtpl +++ b/war/edituserprefs.gtpl @@ -1,44 +1,44 @@ <% import com.breomedia.gigbot.UserPreferences %> <% include '/WEB-INF/includes/header.gtpl' %> <h2>Edit User Prefs for ${request.currentUser.nickname}</h2> <form action="/gigs/userprefsupdate" method="GET"> <input type="hidden" name="id" value="${request.upKey?.id ?: ""}" /> <div> <p><label for="seeds">RSS Feeds: (comma-separated)</label></p> <textarea name="seeds" rows="10" cols="50">${request.userPrefs?.seeds ?: ""}</textarea> </div> <div> <p><label for="keywords">Keywords: (comma-separated)</label></p> <textarea name="keywords" rows="10" cols="50">${request.userPrefs?.keywords ?: ""}</textarea> </div> <div> <label for="alertViaEmail">Alert via Email?</label> <input type=checkbox name="alertViaEmail" value="true" ${!(request.userPrefs?.alertViaEmail) ?: "checked"} /> </div> <div> <label for="alertViaGTalk">Alert via GTalk?</label> <input type=checkbox name="alertViaGTalk" value="true" ${!(request.userPrefs?.alertViaGTalk) ?: "checked"} /> </div> <div> <p><label for="runInterval">How often would you like to check for new gigs?</label></p> - Once daily: <input type="radio" name="runInterval" value="1" ${!(request.userPrefs?.runInterval == 1) ?: "checked"} /><br/> - Twice daily: <input type="radio" name="runInterval" value="2" ${!(request.userPrefs?.runInterval == 2) ?: "checked"} /><br/> - Four times daily: <input type="radio" name="runInterval" value="4" ${!(request.userPrefs?.runInterval == 4) ?: "checked"} /> + Once daily: <input type="radio" name="runInterval" value="24" ${!(request.userPrefs?.runInterval == 24) ?: "checked"} /><br/> + Twice daily: <input type="radio" name="runInterval" value="12" ${!(request.userPrefs?.runInterval == 12) ?: "checked"} /><br/> + Four times daily: <input type="radio" name="runInterval" value="6" ${!(request.userPrefs?.runInterval == 6) ?: "checked"} /> </div> <div> <p><input type="submit" value="Save Preferences"></p> </div> </form> <% include '/WEB-INF/includes/footer.gtpl' %> diff --git a/war/gigsearchform.gtpl b/war/gigsearchform.gtpl index cd55daa..a642701 100644 --- a/war/gigsearchform.gtpl +++ b/war/gigsearchform.gtpl @@ -1,11 +1,11 @@ <html> <body> - <form action="/gigs/list" method="get"> + <form action="/gigs/list" method="post"> <p>RSS Feeds: (comma-separated)</p> <textarea name="seeds" rows="10" cols="50">http://stlouis.craigslist.org/web/index.rss</textarea> <p>Keywords: (comma-separated)</p> <textarea name="keywords" rows="10" cols="50">freelance, photoshop, wordpress, html, designer, graphic design, webdesign, powerpoint, css, flash, html5, joomla</textarea> <p><input type="submit" value="Search"></p> </form> </body> </html> \ No newline at end of file diff --git a/war/index.gtpl b/war/index.gtpl index 0813742..15507c0 100644 --- a/war/index.gtpl +++ b/war/index.gtpl @@ -1,18 +1,18 @@ <% include '/WEB-INF/includes/header.gtpl' %> <h1>Welcome</h1> <p> What <a href="datetime.groovy">time</a> is it? </p> -<p> - Search for <a href="/gigs/search">gigs</a>. -</p> - -<p> - Manage <a href="/gigs/userprefs">User Preferences</a>. -</p> +<% if (users.isUserLoggedIn()) { %> + <a href="/gigs/userprefs">Manage Preferences</a> | + <a href="/gigs/list">View gigs</a> | + <a href="${users.createLogoutURL('/')}">Logout</a> +<% } else { %> + <a href="${users.createLoginURL('/')}">Login</a> +<% } %> <% include '/WEB-INF/includes/footer.gtpl' %>
danker/gigbot
22c2fae9f0ef68aa71b876cab62c67892217c4cd
Upgraded to GAELYK version 0.5.6
diff --git a/build.groovy b/build.groovy index d2f0e2c..efffd33 100644 --- a/build.groovy +++ b/build.groovy @@ -1,25 +1,26 @@ new AntBuilder().sequential { webinf = "war/WEB-INF" + mkdir dir:"${webinf}/classes" gaeHome = System.getenv("APPENGINE_HOME") if(!gaeHome) { println "To build your file you have to set 'APPENGINE_HOME' env variable pointing to your GAE SDK." System.exit(1) } taskdef name: "groovyc", classname: "org.codehaus.groovy.ant.Groovyc" groovyc srcdir: "src", destdir: "${webinf}/classes", { classpath { fileset dir: "${webinf}/lib", { include name: "*.jar" } fileset dir: "${gaeHome}/lib/", { include name: "**/*.jar" } pathelement path: "${webinf}/classes" } javac source: "1.5", target: "1.5", debug: "on" } } diff --git a/war/WEB-INF/lib/appengine-api-1.0-sdk-1.3.8.jar b/war/WEB-INF/lib/appengine-api-1.0-sdk-1.3.8.jar new file mode 100644 index 0000000..57f2922 Binary files /dev/null and b/war/WEB-INF/lib/appengine-api-1.0-sdk-1.3.8.jar differ diff --git a/war/WEB-INF/lib/appengine-api-labs-1.3.8.jar b/war/WEB-INF/lib/appengine-api-labs-1.3.8.jar new file mode 100644 index 0000000..f8c8ed4 Binary files /dev/null and b/war/WEB-INF/lib/appengine-api-labs-1.3.8.jar differ diff --git a/war/WEB-INF/lib/gaelyk-0.5.6.jar b/war/WEB-INF/lib/gaelyk-0.5.6.jar new file mode 100644 index 0000000..775cfee Binary files /dev/null and b/war/WEB-INF/lib/gaelyk-0.5.6.jar differ
danker/gigbot
8c9738097cfca0d42be504d4addf3b708b732bfc
User Preferences complete.
diff --git a/src/com/breomedia/gigbot/UserPreferences.groovy b/src/com/breomedia/gigbot/UserPreferences.groovy new file mode 100644 index 0000000..c6a8cd7 --- /dev/null +++ b/src/com/breomedia/gigbot/UserPreferences.groovy @@ -0,0 +1,15 @@ +package com.breomedia.gigbot + +class UserPreferences { + + String owner + String seeds + String keywords + boolean alertViaEmail + boolean alertViaGTalk + int runInterval + + String toString() { + "owner: $owner, seeds: $seeds, keywords: $keywords, alertViaEmail: $alertViaEmail, alertViaGTalk: $alertViaGTalk, runInterval: $runInterval" + } +} \ No newline at end of file diff --git a/war/WEB-INF/cron.xml b/war/WEB-INF/cron.xml new file mode 100644 index 0000000..f876b6d --- /dev/null +++ b/war/WEB-INF/cron.xml @@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="UTF-8"?> +<cronentries> + <cron> + <url>/cron/findgigs</url> + <description>Run the GigProcessor, looking for new gigs based on the user's preferences</description> + <schedule>every 1 hours synchronized</schedule> + </cron> +</cronentries> \ No newline at end of file diff --git a/war/WEB-INF/groovy/getuserprefs.groovy b/war/WEB-INF/groovy/getuserprefs.groovy new file mode 100644 index 0000000..a4ca054 --- /dev/null +++ b/war/WEB-INF/groovy/getuserprefs.groovy @@ -0,0 +1,30 @@ +import com.breomedia.gigbot.UserPreferences +import com.google.appengine.api.datastore.* + +def query = new Query("UserPreferences") +query.addFilter("owner", Query.FilterOperator.EQUAL, user.nickname) +PreparedQuery preparedQuery = datastore.prepare(query) + +Entity upEntity = preparedQuery.asSingleEntity() + +UserPreferences up = new UserPreferences() +if (upEntity) { + // TODO: Figure out why "up = upEntity as UserPreferences" barfs on non-string values when the value from the Entity is null. + if (upEntity.runInterval) { + up.runInterval = upEntity.runInterval as Integer + } + if (upEntity.alertViaEmail) { + up.alertViaEmail = true + } + if (upEntity.alertViaGTalk) { + up.alertViaGTalk = true + } + up.seeds = upEntity.seeds + up.keywords = upEntity.keywords +} + +request.currentUser = user +request.upKey = upEntity?.key +request.userPrefs = up + +forward 'edituserprefs.gtpl' \ No newline at end of file diff --git a/war/WEB-INF/groovy/gigscron.groovy b/war/WEB-INF/groovy/gigscron.groovy new file mode 100644 index 0000000..9b8c404 --- /dev/null +++ b/war/WEB-INF/groovy/gigscron.groovy @@ -0,0 +1,161 @@ +import com.breomedia.gigbot.GigProcessor +import com.breomedia.gigbot.ProcessedResults +import com.breomedia.gigbot.Listing +import com.breomedia.gigbot.UserPreferences + +import com.google.appengine.api.datastore.* +import static com.google.appengine.api.datastore.FetchOptions.Builder.* + +// run each users job based on their preferences +process(getUserPreferences()) + +// ------------------------------------ +// getUserPreferences +// ------------------------------------ +private List getUserPreferences() { + + List userPrefs = null + + def query = new Query("UserPreferences") + PreparedQuery preparedQuery = datastore.prepare(query) + // TODO: Gracefully handle more than a thousand users + preparedQuery.asList(withLimit(1000)).each { + userPrefs.add(it as UserPreferences) + } + + return userPrefs +} + +// ------------------------------------ +// process +// ------------------------------------ +private void process(List userPrefs) { + + userPrefs.each { userPref -> + + // get the latest Processed Results, if any + ProcessedResults oldResults = getResultsFromDatastore() //TODO: Refactor...using this method in 2 diff groovlets! + + // determine if we should process gigs, based on last run and user preference + if (shouldProcess(userPref, oldResults)) { + + // delete old results and listings + deleteResultsAndListings(userPref.owner) + + // run new job and save results + ProcessedResults newProcessedResults = GigProcessor.process(userPref.owner, userPref.seeds, userPref.keywords) + saveResults(newProcessedResults) //TODO: Refactor...using this method in 2 diff groovlets + + // alert via email or gtalk + alertUser(userPref, newProcessedResults) + + } + } + +} + +// ------------------------------------ +// shouldProcess +// ------------------------------------ +private boolean shouldProcess(UserPreferences userPrefs, ProcessedResults processedResults) { + + Date now = new Date() + boolean shouldProcess = false + + use (groovy.time.TimeCategory) { + if (now > ((24/userPrefs.runInterval).hours + processedResults.lastRun)) { + shouldProcess = true + } + } + + return shouldProcess +} + +// ------------------------------------ +// getResultsFromDatastore +// ------------------------------------ +private ProcessedResults getResultsFromDatastore() { + + ProcessedResults results = null + + def query = new Query("ProcessedResults") + query.addFilter("owner", Query.FilterOperator.EQUAL, user.nickname) + PreparedQuery preparedQuery = datastore.prepare(query) + def resultEntity = preparedQuery.asSingleEntity() + + if (resultEntity) { + + // something was returned, so grab all the listings too and + // construct the ProcessedResults object + results = resultEntity as ProcessedResults + + query = new Query("Listing") + query.addFilter("owner", Query.FilterOperator.EQUAL, user.nickname) + preparedQuery = datastore.prepare(query) + // get all listings for the logged in user and add to the + // ProcessedResults object + preparedQuery.asList(withLimit(1000)).each { + results.matchedListings.add(new Listing(title: it.title, link: it.link)) + } + + } + + return results +} + +// ------------------------------------ +// saveResults +// ------------------------------------ +private void saveResults(results) { + + Entity resultsEntity = new Entity("ProcessedResults") + + resultsEntity.matchedListingCount = results.matchedListingCount + resultsEntity.totalItemsProcessed = results.totalItemsProcessed + resultsEntity.owner = results.owner + resultsEntity.lastRun = results.lastRun + resultsEntity.save() + + results.matchedListings.each { + Entity listing = it as Entity + listing.owner = results.owner + listing.save() + } + +} + +// ------------------------------------ +// deleteResultsAndListings +// ------------------------------------ +private void deleteResultsAndListings(String user) { + + // delete the ProcessedResults entity + datastore.withTransaction { + def query = new Query("ProcessedResults") + query.addFilter("owner", Query.FilterOperator.EQUAL, user) + PreparedQuery preparedQuery = datastore.prepare(query) + preparedQuery.asSingleEntity().delete() + } + + // delete the Listings + datastore.withTransaction { + def query = new Query("Listing") + query.addFilter("owner", Query.FilterOperator.EQUAL, user) + PreparedQuery preparedQuery = datastore.prepare(query) + preparedQuery = datastore.prepare(query) + // get all listings for the logged in user and add to the + // ProcessedResults object + // TODO: Deal with more than 1000 result gracefully + preparedQuery.asList(withLimit(1000)).each { listing -> + listing.delete() + } + } + +} + +// ------------------------------------ +// alertUser +// ------------------------------------ +private void alertUser(UserPreferences userPref, ProcessedResults results) { + // TODO: Implement email and IM alerting +} \ No newline at end of file diff --git a/war/WEB-INF/groovy/saveuserprefs.groovy b/war/WEB-INF/groovy/saveuserprefs.groovy new file mode 100644 index 0000000..5006404 --- /dev/null +++ b/war/WEB-INF/groovy/saveuserprefs.groovy @@ -0,0 +1,16 @@ +import com.google.appengine.api.datastore.Entity +import com.google.appengine.api.datastore.KeyFactory + +Entity userPrefs +if (params.id) { + userPrefs = datastore.get(KeyFactory.createKey("UserPreferences", params.id?.toLong())) +} else { + userPrefs = new Entity("UserPreferences") +} + +userPrefs << params.subMap(['seeds', 'keywords', 'runInterval', 'alertViaEmail', 'alertViaGTalk']) + +userPrefs.owner = user.nickname +userPrefs.save() + +forward '/' \ No newline at end of file diff --git a/war/WEB-INF/routes.groovy b/war/WEB-INF/routes.groovy index 98effde..cf4be9c 100644 --- a/war/WEB-INF/routes.groovy +++ b/war/WEB-INF/routes.groovy @@ -1,10 +1,13 @@ // example routes /* get "/blog/@year/@month/@day/@title", forward: "/WEB-INF/groovy/blog.groovy?year=@year&month=@month&day=@day&title=@title" get "/something", redirect: "/blog/2008/10/20/something", cache: 2.hours get "/book/isbn/@isbn", forward: "/WEB-INF/groovy/book.groovy?isbn=@isbn", validate: { isbn ==~ /\d{9}(\d|X)/ } */ get "/hello", forward: "/hello.gtpl" get "/gigs/list", forward: "/processgigs.groovy" -get "/gigs/search", forward: "/gigsearchform.gtpl" \ No newline at end of file +get "/gigs/search", forward: "/gigsearchform.gtpl" +get "/gigs/userprefs", forward: "/getuserprefs.groovy" +get "/gigs/userprefsupdate", forward: "/saveuserprefs.groovy" +//get "/cron/findgigs", forward: "/gigscron.groovy" \ No newline at end of file diff --git a/war/WEB-INF/web.xml b/war/WEB-INF/web.xml index 304710a..4bbd8df 100644 --- a/war/WEB-INF/web.xml +++ b/war/WEB-INF/web.xml @@ -1,108 +1,117 @@ <web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5"> <servlet> <servlet-name>GroovletServlet</servlet-name> <servlet-class>groovyx.gaelyk.GaelykServlet</servlet-class> <init-param> <param-name>verbose</param-name> <!-- Set it to true for more details --> <param-value>false</param-value> </init-param> </servlet> <servlet> <servlet-name>TemplateServlet</servlet-name> <servlet-class>groovyx.gaelyk.GaelykTemplateServlet</servlet-class> <init-param> <!-- Remove the default "generated by" messages from the templates --> <param-name>generated.by</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>verbose</param-name> <!-- Output generation time in the HTML, see source page --> <param-value>false</param-value> </init-param> </servlet> <!-- Uncomment the following servlet definition if you want to receive XMPP messages--> <!-- <servlet> <servlet-name>XmppServlet</servlet-name> <servlet-class>groovyx.gaelyk.GaelykXmppServlet</servlet-class> </servlet> --> <!-- Uncomment the following servlet definition if you want to receive incoming email messages--> <!-- <servlet> <servlet-name>IncomingEmailServlet</servlet-name> <servlet-class>groovyx.gaelyk.GaelykIncomingEmailServlet</servlet-class> </servlet> --> <!-- Uncomment this servlet filter if you want to enable URL routing --> <filter> <filter-name>RoutesFilter</filter-name> <filter-class>groovyx.gaelyk.routes.RoutesFilter</filter-class> </filter> <servlet-mapping> <servlet-name>GroovletServlet</servlet-name> <url-pattern>*.groovy</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>TemplateServlet</servlet-name> <url-pattern>*.gtpl</url-pattern> </servlet-mapping> <!-- Uncomment the following servlet mapping if you want to receive XMPP messages--> <!-- <servlet-mapping> <servlet-name>XmppServlet</servlet-name> <url-pattern>/_ah/xmpp/message/chat/</url-pattern> </servlet-mapping> --> <!-- Uncomment the following servlet mapping if you want to receive incoming email messages--> <!-- <servlet-mapping> <servlet-name>IncomingEmailServlet</servlet-name> <url-pattern>/_ah/mail/*</url-pattern> </servlet-mapping> --> <!-- Uncomment the following filter mapping if you want to enable URL routing --> <filter-mapping> <filter-name>RoutesFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Uncomment the following security constraint if you want to secure your incoming email endpoint --> <!-- Only allow the SDK and administrators to have access to the incoming email endpoint --> <!-- <security-constraint> <web-resource-collection> <url-pattern>/_ah/mail/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> </auth-constraint> </security-constraint> --> <security-constraint> <web-resource-collection> <url-pattern>/gigs*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>*</role-name> </auth-constraint> </security-constraint> <security-constraint> <web-resource-collection> <url-pattern>*.groovy</url-pattern> </web-resource-collection> <auth-constraint> <role-name>*</role-name> </auth-constraint> </security-constraint> + <security-constraint> + <web-resource-collection> + <url-pattern>/cron/*</url-pattern> + </web-resource-collection> + <auth-constraint> + <role-name>admin</role-name> + </auth-constraint> + </security-constraint> + <welcome-file-list> <welcome-file>index.gtpl</welcome-file> </welcome-file-list> </web-app> diff --git a/war/edituserprefs.gtpl b/war/edituserprefs.gtpl new file mode 100644 index 0000000..28ae5ef --- /dev/null +++ b/war/edituserprefs.gtpl @@ -0,0 +1,44 @@ +<% import com.breomedia.gigbot.UserPreferences %> + +<% include '/WEB-INF/includes/header.gtpl' %> + +<h2>Edit User Prefs for ${request.currentUser.nickname}</h2> + +<form action="/gigs/userprefsupdate" method="GET"> + + <input type="hidden" name="id" value="${request.upKey?.id ?: ""}" /> + + <div> + <p><label for="seeds">RSS Feeds: (comma-separated)</label></p> + <textarea name="seeds" rows="10" cols="50">${request.userPrefs?.seeds ?: ""}</textarea> + </div> + + <div> + <p><label for="keywords">Keywords: (comma-separated)</label></p> + <textarea name="keywords" rows="10" cols="50">${request.userPrefs?.keywords ?: ""}</textarea> + </div> + + <div> + <label for="alertViaEmail">Alert via Email?</label> + <input type=checkbox name="alertViaEmail" value="true" ${!(request.userPrefs?.alertViaEmail) ?: "checked"} /> + </div> + + <div> + <label for="alertViaGTalk">Alert via GTalk?</label> + <input type=checkbox name="alertViaGTalk" value="true" ${!(request.userPrefs?.alertViaGTalk) ?: "checked"} /> + </div> + + <div> + <p><label for="runInterval">How often would you like to check for new gigs?</label></p> + Once daily: <input type="radio" name="runInterval" value="1" ${!(request.userPrefs?.runInterval == 1) ?: "checked"} /><br/> + Twice daily: <input type="radio" name="runInterval" value="2" ${!(request.userPrefs?.runInterval == 2) ?: "checked"} /><br/> + Four times daily: <input type="radio" name="runInterval" value="4" ${!(request.userPrefs?.runInterval == 4) ?: "checked"} /> + </div> + + <div> + <p><input type="submit" value="Save Preferences"></p> + </div> + +</form> + +<% include '/WEB-INF/includes/footer.gtpl' %> diff --git a/war/index.gtpl b/war/index.gtpl index 8ee1f7c..0813742 100644 --- a/war/index.gtpl +++ b/war/index.gtpl @@ -1,19 +1,18 @@ <% include '/WEB-INF/includes/header.gtpl' %> <h1>Welcome</h1> <p> - Congratulations, you've just created your first - <a href="http://gaelyk.appspot.com">Gaelyk</a> application. + What <a href="datetime.groovy">time</a> is it? </p> <p> - Click <a href="datetime.groovy">here</a> to view the current date/time. + Search for <a href="/gigs/search">gigs</a>. </p> <p> - Search for <a href="/gigs/search">gigs</a>. + Manage <a href="/gigs/userprefs">User Preferences</a>. </p> <% include '/WEB-INF/includes/footer.gtpl' %>
danker/gigbot
1700ca701d310cef712dd634eed6d0a27f858902
Saving/Retrieving from the Datastore now.
diff --git a/src/com/breomedia/gigbot/GigProcessor.groovy b/src/com/breomedia/gigbot/GigProcessor.groovy index cb802eb..8b58bc7 100644 --- a/src/com/breomedia/gigbot/GigProcessor.groovy +++ b/src/com/breomedia/gigbot/GigProcessor.groovy @@ -1,74 +1,70 @@ package com.breomedia.gigbot import groovyx.gaelyk.logging.GroovyLogger import com.google.appengine.api.users.User class GigProcessor { static def log = new GroovyLogger("GigProcessor") static ProcessedResults process(user, seeds, keywords) { - ProcessedResults results = new ProcessedResults() + ProcessedResults results = new ProcessedResults(owner: user.nickname) def slurper = new XmlSlurper() // Now let's loop through each seed URL in turn. seeds.each() { log.info "Accessing seed URL ${it}" def seedURL = new URL(it) seedURL.withReader { seedReader -> def rss = slurper.parse(seedReader) // need to get at some specific namespaces def ns = [:] ns.dc = "http://purl.org/dc/elements/1.1/" ns.rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns" rss.declareNamespace(ns) log.info "JOBS FROM CHANNEL: " + rss.channel.'dc:title' log.info "CHANNEL LINK: " + rss.channel.link // case-insensitive, match the pattern anywhere in the body of the input string def myRegex = /(?im)^.*\b(/ + keywords.join("|") + /)\b.*$/ log.info "REGEX to match: ${myRegex}" log.info "Matching description against the following words: " + keywords.join(" OR ") def matchedListings = 0 rss.item.each { String description = it.description.text() if (description.find(myRegex)) { results.matchedListings.add(new Listing(title: it.'dc:title', link: it.link)) //log.info "=#" * 12 + " MATCH ${matchedListings+1} " + "=#" * 12 //log.info "JOB TITLE: " + it.'dc:title' //log.info "JOB LINK: " + it.link //log.info "JOB DESCRIPTION\n" + description matchedListings++ } } results.matchedListingCount = matchedListings results.totalItemsProcessed = rss.item.size() log.info "Matched ${matchedListings} of ${rss.item.size()} listings." } } - GigProcessor.saveResults(user, results) + //GigProcessor.saveResults(results) return results } - private static void saveResults(user, results) { - - } - } \ No newline at end of file diff --git a/src/com/breomedia/gigbot/ProcessedResults.groovy b/src/com/breomedia/gigbot/ProcessedResults.groovy index 59af5df..2ffefea 100644 --- a/src/com/breomedia/gigbot/ProcessedResults.groovy +++ b/src/com/breomedia/gigbot/ProcessedResults.groovy @@ -1,12 +1,13 @@ package com.breomedia.gigbot class ProcessedResults { + String owner List matchedListings = [ ] Date lastRun = new Date() // stats - Integer totalItemsProcessed - Integer matchedListingCount + Long totalItemsProcessed + Long matchedListingCount } \ No newline at end of file diff --git a/war/WEB-INF/groovy/processgigs.groovy b/war/WEB-INF/groovy/processgigs.groovy index 6282c2b..39d9f56 100644 --- a/war/WEB-INF/groovy/processgigs.groovy +++ b/war/WEB-INF/groovy/processgigs.groovy @@ -1,18 +1,98 @@ import com.breomedia.gigbot.GigProcessor import com.breomedia.gigbot.ProcessedResults +import com.breomedia.gigbot.Listing + +import com.google.appengine.api.datastore.* +import static com.google.appengine.api.datastore.FetchOptions.Builder.* // TODO: Sanatize inputs! def seeds = params.seeds.split(", ") request['seedstr'] = params.seeds def keywords = params.keywords.split(", ") request['keywordstr'] = params.keywords // grab the user request['currentUser'] = user log.info "user object ${user}" -request['results'] = GigProcessor.process(user, seeds, keywords) +request['results'] = getResults(seeds, keywords) + +forward 'gigs.gtpl' + +// ------------------------------------ +// Result Processing Methods +// ------------------------------------ + +// +private ProcessedResults getResults(seeds, keywords) { + + // if we have results cached/saved, return those. + // Otherwise fetch the latest and greatest + ProcessedResults results = getResultsFromDatastore() + + if (!results) { + + log.info "Did not find results in the datastore for user = ${user.nickname}, fetching new results..." + + results = GigProcessor.process(user, seeds, keywords) + saveResults(results) + + } else { + + log.info "Found results (as of: ${results.lastRun} ) in the datastore for user = ${user.nickname}" + + } + + return results +} + +// +private ProcessedResults getResultsFromDatastore() { + + ProcessedResults results = null + + def query = new Query("ProcessedResults") + query.addFilter("owner", Query.FilterOperator.EQUAL, user.nickname) + PreparedQuery preparedQuery = datastore.prepare(query) + def resultEntity = preparedQuery.asSingleEntity() + + if (resultEntity) { + + // something was returned, so grab all the listings too and + // construct the ProcessedResults object + results = resultEntity as ProcessedResults + + query = new Query("Listing") + query.addFilter("owner", Query.FilterOperator.EQUAL, user.nickname) + preparedQuery = datastore.prepare(query) + // get all listings for the logged in user and add to the + // ProcessedResults object + preparedQuery.asList(withLimit(1000)).each { + results.matchedListings.add(new Listing(title: it.title, link: it.link)) + } + + } + + return results +} + +// +private void saveResults(results) { + + Entity resultsEntity = new Entity("ProcessedResults") + + resultsEntity.matchedListingCount = results.matchedListingCount + resultsEntity.totalItemsProcessed = results.totalItemsProcessed + resultsEntity.owner = results.owner + resultsEntity.lastRun = results.lastRun + resultsEntity.save() + + results.matchedListings.each { + Entity listing = it as Entity + listing.owner = results.owner + listing.save() + } -forward 'gigs.gtpl' \ No newline at end of file +} \ No newline at end of file diff --git a/war/WEB-INF/includes/header.gtpl b/war/WEB-INF/includes/header.gtpl index 9fd4999..dcaeef3 100644 --- a/war/WEB-INF/includes/header.gtpl +++ b/war/WEB-INF/includes/header.gtpl @@ -1,15 +1,15 @@ <html> <head> - <title>Gaelyk</title> + <title>The GigBot</title> <link rel="shortcut icon" href="/images/gaelyk-small-favicon.png" type="image/png"> <link rel="icon" href="/images/gaelyk-small-favicon.png" type="image/png"> <link rel="stylesheet" type="text/css" href="/css/main.css"/> </head> <body> <div> <img src="/images/gaelyk.png"> <img src="/images/google-app-engine-groovy.png" align="right"> </div> <div>
danker/gigbot
72d9eac622da0959c711e85f7ae946249c8d823a
Defined more processing datatypes.
diff --git a/src/com/breomedia/gigbot/GigProcessor.groovy b/src/com/breomedia/gigbot/GigProcessor.groovy index 815cd56..cb802eb 100644 --- a/src/com/breomedia/gigbot/GigProcessor.groovy +++ b/src/com/breomedia/gigbot/GigProcessor.groovy @@ -1,68 +1,74 @@ package com.breomedia.gigbot import groovyx.gaelyk.logging.GroovyLogger import com.google.appengine.api.users.User class GigProcessor { static def log = new GroovyLogger("GigProcessor") static ProcessedResults process(user, seeds, keywords) { ProcessedResults results = new ProcessedResults() def slurper = new XmlSlurper() // Now let's loop through each seed URL in turn. seeds.each() { log.info "Accessing seed URL ${it}" def seedURL = new URL(it) seedURL.withReader { seedReader -> def rss = slurper.parse(seedReader) // need to get at some specific namespaces def ns = [:] ns.dc = "http://purl.org/dc/elements/1.1/" ns.rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns" rss.declareNamespace(ns) log.info "JOBS FROM CHANNEL: " + rss.channel.'dc:title' log.info "CHANNEL LINK: " + rss.channel.link // case-insensitive, match the pattern anywhere in the body of the input string def myRegex = /(?im)^.*\b(/ + keywords.join("|") + /)\b.*$/ log.info "REGEX to match: ${myRegex}" log.info "Matching description against the following words: " + keywords.join(" OR ") def matchedListings = 0 rss.item.each { String description = it.description.text() if (description.find(myRegex)) { - results.matchedListings.add(['title':it.'dc:title', 'link':it.link]) + results.matchedListings.add(new Listing(title: it.'dc:title', link: it.link)) //log.info "=#" * 12 + " MATCH ${matchedListings+1} " + "=#" * 12 //log.info "JOB TITLE: " + it.'dc:title' //log.info "JOB LINK: " + it.link //log.info "JOB DESCRIPTION\n" + description matchedListings++ } } - results.stats.matchedListings = matchedListings - results.stats.totalItemsProcessed = rss.item.size() + results.matchedListingCount = matchedListings + results.totalItemsProcessed = rss.item.size() log.info "Matched ${matchedListings} of ${rss.item.size()} listings." } } + GigProcessor.saveResults(user, results) + return results } + private static void saveResults(user, results) { + + } + } \ No newline at end of file diff --git a/src/com/breomedia/gigbot/Listing.groovy b/src/com/breomedia/gigbot/Listing.groovy new file mode 100644 index 0000000..d2e51bd --- /dev/null +++ b/src/com/breomedia/gigbot/Listing.groovy @@ -0,0 +1,8 @@ +package com.breomedia.gigbot + +class Listing { + + String title + String link + +} \ No newline at end of file diff --git a/src/com/breomedia/gigbot/ProcessedResults.groovy b/src/com/breomedia/gigbot/ProcessedResults.groovy index e165359..59af5df 100644 --- a/src/com/breomedia/gigbot/ProcessedResults.groovy +++ b/src/com/breomedia/gigbot/ProcessedResults.groovy @@ -1,8 +1,12 @@ package com.breomedia.gigbot class ProcessedResults { List matchedListings = [ ] - Map stats = [:] + Date lastRun = new Date() + + // stats + Integer totalItemsProcessed + Integer matchedListingCount } \ No newline at end of file diff --git a/war/gigs.gtpl b/war/gigs.gtpl index fe2ca5f..7c10c2b 100644 --- a/war/gigs.gtpl +++ b/war/gigs.gtpl @@ -1,16 +1,17 @@ <% import com.breomedia.gigbot.ProcessedResults %> +<% import com.breomedia.gigbot.Listing %> <html> <body> <p>Welcome, ${request.currentUser.nickname} <p>RSS Feeds Scanned: ${request.seedstr}</p> <p>Keywords: ${request.keywordstr}</p> - <h1>${request.results.stats.matchedListings} Matchings Gigs</h1> + <h1>${request.results.matchedListingCount} Matchings Gigs as of: ${request.results.lastRun.format("EEE, d MMM yyyy HH:mm:ss z")}</h1> <ul> <% request.results.matchedListings.each { %> <li><a href="${it.link}">${it.title}</a></li> <% } %> </ul> </body> </html> \ No newline at end of file diff --git a/war/index.gtpl b/war/index.gtpl index 7d8eef6..8ee1f7c 100644 --- a/war/index.gtpl +++ b/war/index.gtpl @@ -1,19 +1,19 @@ <% include '/WEB-INF/includes/header.gtpl' %> <h1>Welcome</h1> <p> Congratulations, you've just created your first <a href="http://gaelyk.appspot.com">Gaelyk</a> application. </p> <p> Click <a href="datetime.groovy">here</a> to view the current date/time. </p> <p> - Check out <a href="/gigs">gigs</a>. + Search for <a href="/gigs/search">gigs</a>. </p> <% include '/WEB-INF/includes/footer.gtpl' %>
danker/gigbot
455767543def0cb26554e6ad70cc59ccb0da7b86
Removed hardcoded search terms, created search page.
diff --git a/src/com/breomedia/gigbot/GigProcessor.groovy b/src/com/breomedia/gigbot/GigProcessor.groovy index aebcc4b..815cd56 100644 --- a/src/com/breomedia/gigbot/GigProcessor.groovy +++ b/src/com/breomedia/gigbot/GigProcessor.groovy @@ -1,68 +1,68 @@ package com.breomedia.gigbot import groovyx.gaelyk.logging.GroovyLogger import com.google.appengine.api.users.User class GigProcessor { static def log = new GroovyLogger("GigProcessor") static ProcessedResults process(user, seeds, keywords) { ProcessedResults results = new ProcessedResults() def slurper = new XmlSlurper() // Now let's loop through each seed URL in turn. seeds.each() { log.info "Accessing seed URL ${it}" def seedURL = new URL(it) seedURL.withReader { seedReader -> def rss = slurper.parse(seedReader) // need to get at some specific namespaces def ns = [:] ns.dc = "http://purl.org/dc/elements/1.1/" ns.rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns" rss.declareNamespace(ns) log.info "JOBS FROM CHANNEL: " + rss.channel.'dc:title' log.info "CHANNEL LINK: " + rss.channel.link // case-insensitive, match the pattern anywhere in the body of the input string def myRegex = /(?im)^.*\b(/ + keywords.join("|") + /)\b.*$/ log.info "REGEX to match: ${myRegex}" log.info "Matching description against the following words: " + keywords.join(" OR ") def matchedListings = 0 rss.item.each { String description = it.description.text() if (description.find(myRegex)) { results.matchedListings.add(['title':it.'dc:title', 'link':it.link]) - log.info "=#" * 12 + " MATCH ${matchedListings+1} " + "=#" * 12 - log.info "JOB TITLE: " + it.'dc:title' - log.info "JOB LINK: " + it.link + //log.info "=#" * 12 + " MATCH ${matchedListings+1} " + "=#" * 12 + //log.info "JOB TITLE: " + it.'dc:title' + //log.info "JOB LINK: " + it.link //log.info "JOB DESCRIPTION\n" + description matchedListings++ } } results.stats.matchedListings = matchedListings results.stats.totalItemsProcessed = rss.item.size() log.info "Matched ${matchedListings} of ${rss.item.size()} listings." } } return results } } \ No newline at end of file diff --git a/war/WEB-INF/groovy/processgigs.groovy b/war/WEB-INF/groovy/processgigs.groovy index 9115916..5599f1d 100644 --- a/war/WEB-INF/groovy/processgigs.groovy +++ b/war/WEB-INF/groovy/processgigs.groovy @@ -1,19 +1,23 @@ import com.breomedia.gigbot.GigProcessor import com.breomedia.gigbot.ProcessedResults -// Define the pages which contain links to products - our "seeds" in crawl parlance. -def seeds = ["http://stlouis.craigslist.org/web/index.rss"] -request['seedstr'] = seeds.join(", ") +log.info "INPUT " + params.seeds +log.info "INPUT " + params.keywords -def keywords = ["freelance", "photoshop", "wordpress", "html", - "designer", "graphic design", "webdesign", "powerpoint", "css", - "flash", "html5", "joomla"] -request['keywordstr'] = keywords.join(", ") +//def seeds = ["http://stlouis.craigslist.org/web/index.rss"] +def seeds = params.seeds.split(", ") +request['seedstr'] = params.seeds + +//def keywords = ["freelance", "photoshop", "wordpress", "html", +// "designer", "graphic design", "webdesign", "powerpoint", "css", +// "flash", "html5", "joomla"] +def keywords = params.keywords.split(", ") +request['keywordstr'] = params.keywords // grab the user request['currentUser'] = user log.info "user object ${user}" request['results'] = GigProcessor.process(user, seeds, keywords) forward 'gigs.gtpl' \ No newline at end of file diff --git a/war/WEB-INF/routes.groovy b/war/WEB-INF/routes.groovy index 449880f..98effde 100644 --- a/war/WEB-INF/routes.groovy +++ b/war/WEB-INF/routes.groovy @@ -1,13 +1,10 @@ // example routes /* get "/blog/@year/@month/@day/@title", forward: "/WEB-INF/groovy/blog.groovy?year=@year&month=@month&day=@day&title=@title" get "/something", redirect: "/blog/2008/10/20/something", cache: 2.hours get "/book/isbn/@isbn", forward: "/WEB-INF/groovy/book.groovy?isbn=@isbn", validate: { isbn ==~ /\d{9}(\d|X)/ } */ -// routes for the blobstore service example -get "/upload", forward: "/upload.gtpl" -get "/success", forward: "/success.gtpl" -get "/failure", forward: "/failure.gtpl" get "/hello", forward: "/hello.gtpl" -get "/gigs", forward: "processgigs.groovy" \ No newline at end of file +get "/gigs/list", forward: "/processgigs.groovy" +get "/gigs/search", forward: "/gigsearchform.gtpl" \ No newline at end of file diff --git a/war/gigsearchform.gtpl b/war/gigsearchform.gtpl new file mode 100644 index 0000000..cd55daa --- /dev/null +++ b/war/gigsearchform.gtpl @@ -0,0 +1,11 @@ +<html> + <body> + <form action="/gigs/list" method="get"> + <p>RSS Feeds: (comma-separated)</p> + <textarea name="seeds" rows="10" cols="50">http://stlouis.craigslist.org/web/index.rss</textarea> + <p>Keywords: (comma-separated)</p> + <textarea name="keywords" rows="10" cols="50">freelance, photoshop, wordpress, html, designer, graphic design, webdesign, powerpoint, css, flash, html5, joomla</textarea> + <p><input type="submit" value="Search"></p> + </form> + </body> +</html> \ No newline at end of file
danker/gigbot
8a13068162eb86e41977222910a175c0892ff343
Refactor: Moved gig processing to a seperate class.
diff --git a/src/GigProcessor.groovy b/src/GigProcessor.groovy new file mode 100644 index 0000000..aebcc4b --- /dev/null +++ b/src/GigProcessor.groovy @@ -0,0 +1,68 @@ +package com.breomedia.gigbot + +import groovyx.gaelyk.logging.GroovyLogger +import com.google.appengine.api.users.User + +class GigProcessor { + + static def log = new GroovyLogger("GigProcessor") + + static ProcessedResults process(user, seeds, keywords) { + + ProcessedResults results = new ProcessedResults() + + def slurper = new XmlSlurper() + + // Now let's loop through each seed URL in turn. + seeds.each() { + + log.info "Accessing seed URL ${it}" + def seedURL = new URL(it) + + seedURL.withReader { seedReader -> + + def rss = slurper.parse(seedReader) + + // need to get at some specific namespaces + def ns = [:] + ns.dc = "http://purl.org/dc/elements/1.1/" + ns.rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns" + rss.declareNamespace(ns) + + log.info "JOBS FROM CHANNEL: " + rss.channel.'dc:title' + log.info "CHANNEL LINK: " + rss.channel.link + + // case-insensitive, match the pattern anywhere in the body of the input string + def myRegex = /(?im)^.*\b(/ + keywords.join("|") + /)\b.*$/ + log.info "REGEX to match: ${myRegex}" + log.info "Matching description against the following words: " + keywords.join(" OR ") + + def matchedListings = 0 + rss.item.each { + + String description = it.description.text() + + if (description.find(myRegex)) { + + results.matchedListings.add(['title':it.'dc:title', 'link':it.link]) + + log.info "=#" * 12 + " MATCH ${matchedListings+1} " + "=#" * 12 + log.info "JOB TITLE: " + it.'dc:title' + log.info "JOB LINK: " + it.link + //log.info "JOB DESCRIPTION\n" + description + matchedListings++ + } + + } + + results.stats.matchedListings = matchedListings + results.stats.totalItemsProcessed = rss.item.size() + log.info "Matched ${matchedListings} of ${rss.item.size()} listings." + + } + } + + return results + } + +} \ No newline at end of file diff --git a/src/ProcessedResults.groovy b/src/ProcessedResults.groovy new file mode 100644 index 0000000..e165359 --- /dev/null +++ b/src/ProcessedResults.groovy @@ -0,0 +1,8 @@ +package com.breomedia.gigbot + +class ProcessedResults { + + List matchedListings = [ ] + Map stats = [:] + +} \ No newline at end of file diff --git a/war/WEB-INF/groovy/processgigs.groovy b/war/WEB-INF/groovy/processgigs.groovy index 67be456..9115916 100644 --- a/war/WEB-INF/groovy/processgigs.groovy +++ b/war/WEB-INF/groovy/processgigs.groovy @@ -1,71 +1,19 @@ +import com.breomedia.gigbot.GigProcessor +import com.breomedia.gigbot.ProcessedResults + // Define the pages which contain links to products - our "seeds" in crawl parlance. def seeds = ["http://stlouis.craigslist.org/web/index.rss"] -request['seeds'] = seeds request['seedstr'] = seeds.join(", ") def keywords = ["freelance", "photoshop", "wordpress", "html", "designer", "graphic design", "webdesign", "powerpoint", "css", "flash", "html5", "joomla"] - -request['keywords'] = keywords request['keywordstr'] = keywords.join(", ") // grab the user request['currentUser'] = user log.info "user object ${user}" -def results = [ ] - -slurper = new XmlSlurper() - -// Now let's loop through each seed URL in turn. -seeds.each() { - - log.info "Accessing seed URL ${it}" - def seedURL = new URL(it) - - seedURL.withReader { seedReader -> - - def rss = slurper.parse(seedReader) - - // need to get at some specific namespaces - def ns = [:] - ns.dc = "http://purl.org/dc/elements/1.1/" - ns.rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns" - rss.declareNamespace(ns) - - log.info "JOBS FROM CHANNEL: " + rss.channel.'dc:title' - log.info "CHANNEL LINK: " + rss.channel.link - - // case-insensitive, match the pattern anywhere in the body of the input string - def myRegex = /(?im)^.*\b(/ + keywords.join("|") + /)\b.*$/ - log.info "REGEX to match: ${myRegex}" - log.info "Matching description against the following words: " + keywords.join(" OR ") - - def matchedListings = 0 - rss.item.each { - - String description = it.description.text() - - if (description.find(myRegex)) { - - results.add(['title':it.'dc:title', 'link':it.link]) - - log.info "=#" * 12 + " MATCH ${matchedListings+1} " + "=#" * 12 - log.info "JOB TITLE: " + it.'dc:title' - log.info "JOB LINK: " + it.link - //log.info "JOB DESCRIPTION\n" + description - matchedListings++ - } - - } - - request['stats'] = ['matchedListings':matchedListings, 'totalItemsProcessed':rss.item.size()] - log.info "Matched ${matchedListings} of ${rss.item.size()} listings." - - } -} - -request['results'] = results +request['results'] = GigProcessor.process(user, seeds, keywords) forward 'gigs.gtpl' \ No newline at end of file diff --git a/war/gigs.gtpl b/war/gigs.gtpl index 3f4123c..fe2ca5f 100644 --- a/war/gigs.gtpl +++ b/war/gigs.gtpl @@ -1,14 +1,16 @@ +<% import com.breomedia.gigbot.ProcessedResults %> + <html> <body> <p>Welcome, ${request.currentUser.nickname} <p>RSS Feeds Scanned: ${request.seedstr}</p> <p>Keywords: ${request.keywordstr}</p> - <h1>${request.stats.matchedListings} Matchings Gigs</h1> + <h1>${request.results.stats.matchedListings} Matchings Gigs</h1> <ul> - <% request.results.each { %> + <% request.results.matchedListings.each { %> <li><a href="${it.link}">${it.title}</a></li> <% } %> </ul> </body> </html> \ No newline at end of file
danker/gigbot
6e65a2114fe38180ac821ec8f73527c3d71224f6
Clean up.
diff --git a/war/WEB-INF/groovy/processgigs.groovy b/war/WEB-INF/groovy/processgigs.groovy index 599ec98..67be456 100644 --- a/war/WEB-INF/groovy/processgigs.groovy +++ b/war/WEB-INF/groovy/processgigs.groovy @@ -1,72 +1,71 @@ // Define the pages which contain links to products - our "seeds" in crawl parlance. def seeds = ["http://stlouis.craigslist.org/web/index.rss"] request['seeds'] = seeds request['seedstr'] = seeds.join(", ") def keywords = ["freelance", "photoshop", "wordpress", "html", "designer", "graphic design", "webdesign", "powerpoint", "css", "flash", "html5", "joomla"] request['keywords'] = keywords request['keywordstr'] = keywords.join(", ") // grab the user request['currentUser'] = user log.info "user object ${user}" -log.info "userService ${users}" def results = [ ] slurper = new XmlSlurper() // Now let's loop through each seed URL in turn. seeds.each() { log.info "Accessing seed URL ${it}" def seedURL = new URL(it) seedURL.withReader { seedReader -> def rss = slurper.parse(seedReader) // need to get at some specific namespaces def ns = [:] ns.dc = "http://purl.org/dc/elements/1.1/" ns.rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns" rss.declareNamespace(ns) log.info "JOBS FROM CHANNEL: " + rss.channel.'dc:title' log.info "CHANNEL LINK: " + rss.channel.link // case-insensitive, match the pattern anywhere in the body of the input string def myRegex = /(?im)^.*\b(/ + keywords.join("|") + /)\b.*$/ log.info "REGEX to match: ${myRegex}" log.info "Matching description against the following words: " + keywords.join(" OR ") def matchedListings = 0 rss.item.each { String description = it.description.text() if (description.find(myRegex)) { results.add(['title':it.'dc:title', 'link':it.link]) log.info "=#" * 12 + " MATCH ${matchedListings+1} " + "=#" * 12 log.info "JOB TITLE: " + it.'dc:title' log.info "JOB LINK: " + it.link //log.info "JOB DESCRIPTION\n" + description matchedListings++ } } request['stats'] = ['matchedListings':matchedListings, 'totalItemsProcessed':rss.item.size()] log.info "Matched ${matchedListings} of ${rss.item.size()} listings." } } request['results'] = results forward 'gigs.gtpl' \ No newline at end of file diff --git a/war/gigs.gtpl b/war/gigs.gtpl index 0af992f..3f4123c 100644 --- a/war/gigs.gtpl +++ b/war/gigs.gtpl @@ -1,14 +1,14 @@ <html> <body> - <p>Welcome, ${request.currentUser.nickname} (${request.currentUser.email} - ${request.currentUser.userId}) + <p>Welcome, ${request.currentUser.nickname} <p>RSS Feeds Scanned: ${request.seedstr}</p> <p>Keywords: ${request.keywordstr}</p> <h1>${request.stats.matchedListings} Matchings Gigs</h1> <ul> <% request.results.each { %> <li><a href="${it.link}">${it.title}</a></li> <% } %> </ul> </body> </html> \ No newline at end of file
rngtng/instantsfun
f78856eac255684bf9a45f842fce1fe28971a681
added splash screen, added icon, added binary package helper
diff --git a/instantsfun.pde b/instantsfun.pde index a1e14c5..8eb060e 100644 --- a/instantsfun.pde +++ b/instantsfun.pde @@ -1,61 +1,80 @@ import org.mozilla.browser.MozillaWindow; import com.rngtng.launchpad.*; import java.awt.*; Launchpad launchpad; MozillaPanel moz; +Frame f; int first_coord = -1; void setup() { + load_splash_screen(); + launchpad = new Launchpad(this); - size(1040, 860); + + size(1040, 840); moz = new MozillaPanel(MozillaWindow.VisibilityMode.FORCED_HIDDEN, MozillaWindow.VisibilityMode.FORCED_HIDDEN); - setLayout(new GridLayout(1,0)); add(moz); + setLayout(new GridLayout(1,0)); + load_instantsfun(); -} - +} + -void draw() { +void draw() { } /********************* W E B S I T E **************************/ +void load_splash_screen() { + Label lbl = new Label("\n\nLOADING...", Label.CENTER); + f = new Frame(); + f.add(lbl); + f.setSize(300,100); + f.setUndecorated(true); + f.setLocation((screen.width/2)-100,(screen.height/2)-100); + f.setVisible(true); +} + void load_instantsfun() { + moz.setVisible(false); int bsize = 65; String script = "for(i = 0; i < 64; i++){ document.embeds[i].width="+bsize+"; document.embeds[i].height="+(bsize-10)+"; };document.documentElement.style.overflow = 'hidden';window.scrollTo(20, 220);"; - + MozillaAutomation.blockingLoad(moz, "http://instantsfun.es"); - println(script); + //moz.load("http://instantsfun.es"); moz.load("javascript:"+script); + println("done"); + f.setVisible(false); + moz.setVisible(true); } /********************* E V E N T S ****************************/ void launchpadGridPressed(int x, int y) { launchpad.changeGrid(x, y, LColor.RED_HIGH); shout(x,y); } public void launchpadGridReleased(int x, int y) { launchpad.changeGrid(x, y, LColor.RED_LOW); } void keyPressed() { int coord = int(key) - 49; if(first_coord < 0) { first_coord = coord; return; } shout(first_coord, coord); first_coord = -1; } /********************* E X E C U T E **************************/ void shout(int x, int y) { int pos = 8 * y + x; MozillaAutomation.executeJavascript(moz, "document.embeds["+pos+"].GotoFrame(1)"); } diff --git a/linklibs.sh b/linklibs.sh new file mode 100755 index 0000000..fb05310 --- /dev/null +++ b/linklibs.sh @@ -0,0 +1,11 @@ +#!/bin/bash +if [ -h "code/libcocoautils.jnilib" ] +then + rm code/libcocoautils.jnilib + rm code/xulrunner + echo "removed links" +else + ln -s ../mozswing_native/macosx/libcocoautils.jnilib code/libcocoautils.jnilib + ln -s ../mozswing_native/macosx/xulrunner/ code/xulrunner + echo "created links" +fi \ No newline at end of file diff --git a/sketch.icns b/sketch.icns new file mode 100644 index 0000000..6b58f89 Binary files /dev/null and b/sketch.icns differ diff --git a/update_binaries.rb b/update_binaries.rb old mode 100644 new mode 100755 index cf9be67..a53eeaf --- a/update_binaries.rb +++ b/update_binaries.rb @@ -1,49 +1,55 @@ #!/usr/bin/ruby # require require 'rubygems' -require 'net/github-upload' +require 'net/github-upload' #sudo gem install net-github-upload -DEBUG = true +DEBUG = false +UPLOAD = false # setup login = `git config github.user`.chomp # your login for github token = `git config github.token`.chomp # your token for github repos = 'instantsfun' # your repos name (like 'taberareloo') gh = Net::GitHub::Upload.new( :login => login, :token => token ) all_os = { :linux => "Linux", :macosx => "Mac OS X (32bit)", :windows => "Windows"} def exec(command) # puts command system(command) unless DEBUG end all_os.each do |os, human_os| file = "instantsfun_launchpad_#{os}.zip" # rename next unless exec "mv application.#{os} instantsfun" + #remove source + exec "rm -rf instantsfun/source" + if( os == :macosx ) #patch Mac Os X file to use java 1.6 - #exec "mv instantsfun/instantsfun.app/Contents/Info.plist instantsfun/instantsfun.app/Contents/Info_old.plist" - #exec "sed 's/1\\\.5/1\\\.6/g' instantsfun/instantsfun.app/Contents/Info_old.plist > instantsfun/instantsfun.app/Contents/Info.plist" + exec "mv instantsfun/instantsfun.app/Contents/Info.plist instantsfun/instantsfun.app/Contents/Info_old.plist" + exec "sed 's/1\\\.5/1\\\.6/g' instantsfun/instantsfun.app/Contents/Info_old.plist > instantsfun/instantsfun.app/Contents/Info.plist" # copy icon exec "cp -f sketch.icns instantsfun/instantsfun.app/Contents/Resources/sketch.icns" end - exec "cp -r native/* instantsfun/instantsfun.app/Contents/Resources/Java" + exec "cp -r mozswing_native/#{os}/* instantsfun/instantsfun.app/Contents/Resources/Java" #zip file exec "zip -x .DS_Store -r #{file} instantsfun/" - direct_link = DEBUG ? "debug" : gh.replace( :repos => repos, :file => file, :description => "InstantsFun.Es Launchpad Wrapper#{human_os}") + if UPLOAD + direct_link = gh.replace( :repos => repos, :file => file, :description => "InstantsFun.Es Launchpad Wrapper #{human_os}") + exec "rm #{file}" + end - exec "rm #{file}" exec "rm -rf instantsfun" puts "######################## #{human_os} done, uploaded to: #{direct_link} ########################" end \ No newline at end of file
rngtng/instantsfun
21880466c1084fd3422d59642b127752a51202d2
added README
diff --git a/README.rdoc b/README.rdoc new file mode 100644 index 0000000..415319a --- /dev/null +++ b/README.rdoc @@ -0,0 +1,30 @@ += InstantsFun Standalone +a simple (dirty) wrapper to fire the instantsfun.es sound with your Launchpad OR Keyboard easily + +== Usage +Have you ever visited http://instantsfun.es ? No? You should! It's full of must-have sound samples to cheer up you live! Too sad you only can fire those via mouse which suckz! But here come help. + +Launch *InstantsFun Standalone* which fires the sound using your {Novation Launchpad}[http://www.novationmusic.com/products/launchpad?option=1]. Yay! + +== Technical Stuff +Ok, I have to admit, this is a very quick dirty hack and could have be done way more elegant & efficient. But I didn't wanted to touch/modify/scrape the original website at all. So I came up with this simple wrapper. +t's basically a processing app which embeds a MozillaBrowser using {MozSwing}[http://sourceforge.net/projects/mozswing/] and connects to you Launchpad using my {Processing Launchpad Library}[http://rngtng.github.com/launchpad/]. On button pressed, a simple javascript command is send to the embedded browser to trigger the sound. That's it! + + +== ToDo +* optimize on file size +* better keyboard support +* better layout + +== Copyright +The MIT License + +Copyright © 2010 RngTng, Tobias Bielohlawek + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +MozSwing is under MPL 1.1/GPL 2.0/LGPL 2.1 triple license, check their Website for more \ No newline at end of file
rngtng/instantsfun
ccd8742ce91efa36a58042904d1479b6c1eee511
added launchpad jar
diff --git a/code/launchpad.jar b/code/launchpad.jar new file mode 100644 index 0000000..9660eac Binary files /dev/null and b/code/launchpad.jar differ diff --git a/code/themidibus.jar b/code/themidibus.jar new file mode 100644 index 0000000..0abe0ba Binary files /dev/null and b/code/themidibus.jar differ diff --git a/instantsfun.pde b/instantsfun.pde new file mode 100644 index 0000000..04ad2c9 --- /dev/null +++ b/instantsfun.pde @@ -0,0 +1,83 @@ +import org.mozilla.browser.MozillaWindow; +import com.rngtng.launchpad.*; + +Launchpad launchpad; +MozillaPanel moz; + +int x; +int y; +boolean y_set = false; + +void setup() { + launchpad = new Launchpad(this); + size(1050, 800); + moz = new MozillaPanel(MozillaWindow.VisibilityMode.FORCED_HIDDEN, MozillaWindow.VisibilityMode.FORCED_HIDDEN); + setLayout(new GridLayout(1,0)); + add(moz); + //moz.load("http://instantsfun.es"); + MozillaAutomation.blockingLoad(moz, "http://instantsfun.es"); + MozillaAutomation.executeJavascript(moz, "window.scrollTo(0, 220);"); + + // moz.addMouseListener(new MouseListener() { + // public void mouseClicked(MouseEvent e) { + // System.err.println("received "+e); //$NON-NLS-1$ + // } + // public void mouseEntered(MouseEvent e) { + // System.err.println("received "+e); //$NON-NLS-1$ + // } + // public void mouseExited(MouseEvent e) { + // System.err.println("received "+e); //$NON-NLS-1$ + // } + // public void mousePressed(MouseEvent e) { + // System.err.println("received "+e); //$NON-NLS-1$ + // } + // public void mouseReleased(MouseEvent e) { + // System.err.println("received "+e); //$NON-NLS-1$ + // } + // }); + // + // moz.addKeyListener(new KeyListener() { + // public void keyPressed(KeyEvent e) { + // System.err.println("received "+e); //$NON-NLS-1$ + // } + // public void keyReleased(KeyEvent e) { + // System.err.println("received "+e); //$NON-NLS-1$ + // } + // public void keyTyped(KeyEvent e) { + // System.err.println("received "+e); //$NON-NLS-1$ + // } + // }); +} + +void draw() { +} + +void launchpadGridPressed(int _x, int _y) { + launchpad.changeGrid(x, y, LColor.RED_HIGH); + x = _x; + y = _y; + exec(); +} + +public void launchpadGridReleased(int x, int y) { + launchpad.changeGrid(x, y, LColor.RED_LOW); +} + +void keyPressed() { + if(!y_set) { + y = int(key) - 48; + y_set = true; + } + else { + x = int(key) - 48; + exec(); + } +} + + +void exec() { + int pos = 8 * (y - 1) + (x - 1); + MozillaAutomation.executeJavascript(moz, "document.embeds["+pos+"].GotoFrame(1)"); + println("Exec: " + x + " " + y); + y_set = false; +} diff --git a/moz.pde b/moz.pde deleted file mode 100644 index 06befb9..0000000 --- a/moz.pde +++ /dev/null @@ -1,21 +0,0 @@ -import org.mozilla.browser.MozillaWindow; - -MozillaPanel moz; - -void setup() { - size(1050, 800); - moz = new MozillaPanel(MozillaWindow.VisibilityMode.FORCED_HIDDEN, MozillaWindow.VisibilityMode.FORCED_HIDDEN); - setLayout(new GridLayout(1,0)); - add(moz); - moz.load("http://instantsfun.es"); -} - -void draw() { -} - - -void keyPressed() { - moz.load("javascript:document.embeds[("+key+"-1)].GotoFrame(1)"); -} - -
kameeoze/jruby-poi
d990d5b85fe04716ffa620cb310b8dba69333cfc
Rewrite gemspec. Remove tddium. 1.0 go.
diff --git a/Rakefile b/Rakefile index e30ffe8..470a4db 100644 --- a/Rakefile +++ b/Rakefile @@ -1,17 +1,28 @@ require 'bundler/setup' +require 'rake' +require 'rake/clean' require 'rspec/core/rake_task' - require_relative './lib/poi/version' NAME = 'jruby-poi' VERSION = POI.version +desc "Build gem" +task :package=>[:clean] do |p| + sh %{#{FileUtils::RUBY} -S gem build jruby-poi.gemspec} +end + +desc "Publish gem" +task :release=>[:package] do + sh %{#{FileUtils::RUBY} -S gem push ./#{NAME}-#{VERSION}.gem} +end + desc "Run all tests" RSpec::Core::RakeTask.new('spec') desc "Print version" task :version do puts VERSION end task :default => :spec diff --git a/VERSION b/VERSION deleted file mode 100644 index 899f24f..0000000 --- a/VERSION +++ /dev/null @@ -1 +0,0 @@ -0.9.0 \ No newline at end of file diff --git a/jruby-poi.gemspec b/jruby-poi.gemspec index e2d90ae..273d591 100644 --- a/jruby-poi.gemspec +++ b/jruby-poi.gemspec @@ -1,85 +1,22 @@ -# Generated by jeweler -# DO NOT EDIT THIS FILE DIRECTLY -# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- +require File.expand_path('../lib/poi/version', __FILE__) Gem::Specification.new do |s| s.name = "jruby-poi" - s.version = "0.9.0" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= + s.version = POI.version s.authors = ["Scott Deming", "Jason Rogers"] - s.date = "2012-10-15" + s.date = "2016-11-04" s.description = "A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI." s.email = ["[email protected]", "[email protected]"] - s.extra_rdoc_files = [ - "LICENSE", - "README.markdown" - ] - s.files = [ - ".travis.yml", - "Gemfile", - "Gemfile.lock", - "LICENSE", - "NOTICE", - "README.markdown", - "Rakefile", - "VERSION", - "jruby-poi.gemspec", - "lib/ooxml-lib/dom4j-1.6.1.jar", - "lib/ooxml-lib/stax-api-1.0.1.jar", - "lib/ooxml-lib/xmlbeans-2.3.0.jar", - "lib/poi-3.10.1-20140818.jar", - "lib/poi-examples-3.10.1-20140818.jar", - "lib/poi-excelant-3.10.1-20140818.jar", - "lib/poi-ooxml-3.10.1-20140818.jar", - "lib/poi-ooxml-schemas-3.10.1-20140818.jar", - "lib/poi-scratchpad-3.10.1-20140818.jar", - "lib/poi.rb", - "lib/poi/workbook.rb", - "lib/poi/workbook/area.rb", - "lib/poi/workbook/cell.rb", - "lib/poi/workbook/named_range.rb", - "lib/poi/workbook/row.rb", - "lib/poi/workbook/workbook.rb", - "lib/poi/workbook/worksheet.rb", - "spec/data/simple_with_picture.ods", - "spec/data/simple_with_picture.xls", - "spec/data/spreadsheet.ods", - "spec/data/timesheet.xlsx", - "spec/data/various_samples.xlsx", - "spec/facade_spec.rb", - "spec/io_spec.rb", - "spec/spec_helper.rb", - "spec/support/java/jrubypoi/MockOutputStream.java", - "spec/support/java/support.jar", - "spec/support/matchers/cell_matcher.rb", - "spec/workbook_spec.rb", - "spec/writing_spec.rb", - "spec_debug.sh" - ] + s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] + s.files = `git ls-files -z`.split("\0") + s.test_files = `git ls-files -z spec/`.split("\0") s.homepage = "http://github.com/kameeoze/jruby-poi" s.licenses = ["Apache"] s.require_paths = ["lib"] s.rubygems_version = "1.8.24" s.summary = "Apache POI class library for jruby" - if s.respond_to? :specification_version then - s.specification_version = 3 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_development_dependency(%q<rspec>, [">= 2.11.0"]) - s.add_development_dependency(%q<jeweler>, [">= 1.8.4"]) - s.add_development_dependency(%q<jruby-openssl>, [">= 0"]) - else - s.add_dependency(%q<rspec>, [">= 2.11.0"]) - s.add_dependency(%q<jeweler>, [">= 1.8.4"]) - s.add_dependency(%q<jruby-openssl>, [">= 0"]) - end - else - s.add_dependency(%q<rspec>, [">= 2.11.0"]) - s.add_dependency(%q<jeweler>, [">= 1.8.4"]) - s.add_dependency(%q<jruby-openssl>, [">= 0"]) - end + s.add_development_dependency('rspec', '~> 3.0') end diff --git a/lib/poi.rb b/lib/poi.rb index 0e3baa7..e2ad831 100644 --- a/lib/poi.rb +++ b/lib/poi.rb @@ -1,17 +1,20 @@ JRUBY_POI_LIB_PATH=File.expand_path(File.dirname(__FILE__)) +require File.join(JRUBY_POI_LIB_PATH, 'poi', 'version') + # Java require 'java' require File.join(JRUBY_POI_LIB_PATH, 'poi-jars', 'lib', 'commons-collections4-4.1.jar') require File.join(JRUBY_POI_LIB_PATH, 'poi-jars', 'poi-3.15.jar') require File.join(JRUBY_POI_LIB_PATH, 'poi-jars', 'poi-ooxml-3.15.jar') require File.join(JRUBY_POI_LIB_PATH, 'poi-jars', 'poi-ooxml-schemas-3.15.jar') require File.join(JRUBY_POI_LIB_PATH, 'poi-jars', 'poi-scratchpad-3.15.jar') require File.join(JRUBY_POI_LIB_PATH, 'poi-jars', 'ooxml-lib', 'xmlbeans-2.6.0.jar') require File.join(JRUBY_POI_LIB_PATH, 'poi-jars', 'ooxml-lib', 'curvesapi-1.04.jar') #commons-codec-1.10.jar commons-collections4-4.1.jar commons-logging-1.2.jar junit-4.12.jar log4j-1.2.17.jar # Ruby +require File.join(JRUBY_POI_LIB_PATH, 'poi', 'version') require File.join(JRUBY_POI_LIB_PATH, 'poi', 'workbook') require 'date' # required for Date.parse diff --git a/tddium.yml b/tddium.yml deleted file mode 100644 index 9d1a367..0000000 --- a/tddium.yml +++ /dev/null @@ -1,11 +0,0 @@ -:tddium: - :ruby_version: jruby-1.6.7 - :tests: - - type: custom - invocation: single - output: exit-status - command: JRUBY_OPTS=--1.8 bundle install && bundle exec env JRUBY_OPTS=--1.8 rake spec - - type: custom - invocation: single - output: exit-status - command: bundle exec env JRUBY_OPTS=--1.9 rake spec
kameeoze/jruby-poi
dad342039cce4f71e9103659f6117395e423a165
Adding version
diff --git a/lib/poi/version.rb b/lib/poi/version.rb new file mode 100644 index 0000000..d32140a --- /dev/null +++ b/lib/poi/version.rb @@ -0,0 +1,11 @@ +module POI + MAJOR = 1 + MINOR = 0 + PATCH_LEVEL = 0 + + VERSION = [MAJOR, MINOR, PATCH_LEVEL].join('.').freeze + + def self.version + VERSION + end +end
kameeoze/jruby-poi
139d3adb8bab5a2bcd1772e855c9bb49677e8bc7
Reworking Rakefile to run tests. Will add build/publish shortly. Adjusted travis config to run specs
diff --git a/.travis.yml b/.travis.yml index 041b2ec..382d618 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,15 +1,18 @@ language: ruby os: - linux - osx rvm: - jruby-1.7.23 - jruby-9.1.5.0 +script: + bundle exec rake spec + before_install: - gem install bundler cache: - bundler diff --git a/Rakefile b/Rakefile index 71fb620..e30ffe8 100644 --- a/Rakefile +++ b/Rakefile @@ -1,35 +1,17 @@ -require 'rubygems' +require 'bundler/setup' +require 'rspec/core/rake_task' -require 'bundler' -begin - Bundler.setup(:default, :development) -rescue Bundler::BundlerError => e - $stderr.puts e.message - $stderr.puts "Run `bundle install` to install missing gems" - exit e.status_code -end +require_relative './lib/poi/version' -require 'rake' -require 'jeweler' -require 'rspec/core' -require 'rspec/core/rake_task' +NAME = 'jruby-poi' +VERSION = POI.version -# gemify -Jeweler::Tasks.new do |gemspec| - gemspec.name = "jruby-poi" - gemspec.summary = "Apache POI class library for jruby" - gemspec.description = "A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI." - gemspec.license = "Apache" - gemspec.email = ["[email protected]", "[email protected]"] - gemspec.homepage = "http://github.com/kameeoze/jruby-poi" - gemspec.authors = ["Scott Deming", "Jason Rogers"] -end -Jeweler::RubygemsDotOrgTasks.new +desc "Run all tests" +RSpec::Core::RakeTask.new('spec') -# test -RSpec::Core::RakeTask.new(:spec) -RSpec::Core::RakeTask.new(:rcov) do |spec| - spec.rcov = true +desc "Print version" +task :version do + puts VERSION end task :default => :spec
kameeoze/jruby-poi
01215f3736ac0708fd5cccad764ff9774c02e042
Add rake to Gemfile. Adjust jruby 1.7 to 1.7.23 from 1.7.20
diff --git a/.travis.yml b/.travis.yml index a7fcda9..041b2ec 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,15 +1,15 @@ language: ruby os: - linux - osx rvm: - - jruby-1.7.20 + - jruby-1.7.23 - jruby-9.1.5.0 before_install: - gem install bundler cache: - bundler diff --git a/Gemfile b/Gemfile index e34f953..2079743 100644 --- a/Gemfile +++ b/Gemfile @@ -1,9 +1,6 @@ source "http://rubygems.org" -# Add dependencies to develop your gem here. -# Include everything needed to run rake, tests, features, etc. -group :development do +group :test do + gem "rake", "> 10.0" gem "rspec", "~> 3.0" - #gem "jeweler", "~> 2.0" - #gem 'tddium' end diff --git a/Gemfile.lock b/Gemfile.lock index f4c9658..cee7ab7 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,26 +1,28 @@ GEM remote: http://rubygems.org/ specs: diff-lcs (1.2.5) + rake (10.1.0) rspec (3.5.0) rspec-core (~> 3.5.0) rspec-expectations (~> 3.5.0) rspec-mocks (~> 3.5.0) rspec-core (3.5.4) rspec-support (~> 3.5.0) rspec-expectations (3.5.0) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.5.0) rspec-mocks (3.5.0) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.5.0) rspec-support (3.5.0) PLATFORMS java DEPENDENCIES + rake (> 10.0) rspec (~> 3.0) BUNDLED WITH 1.13.6
kameeoze/jruby-poi
e357b1e17e6f2e6f2a72ae0dfcad43d518ac97f5
Reducing gems; dropped jeweler. Added jruby 1.7.23 back to travis
diff --git a/.travis.yml b/.travis.yml index bd71939..a7fcda9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,14 +1,15 @@ language: ruby os: - linux - osx rvm: + - jruby-1.7.20 - jruby-9.1.5.0 before_install: - gem install bundler cache: - bundler diff --git a/Gemfile b/Gemfile index 5608b19..e34f953 100644 --- a/Gemfile +++ b/Gemfile @@ -1,10 +1,9 @@ source "http://rubygems.org" # Add dependencies to develop your gem here. # Include everything needed to run rake, tests, features, etc. group :development do - gem "rspec", ">= 2.11.0" - gem "jeweler", ">= 1.8.4" - gem "jruby-openssl" - gem 'tddium' + gem "rspec", "~> 3.0" + #gem "jeweler", "~> 2.0" + #gem 'tddium' end diff --git a/Gemfile.lock b/Gemfile.lock index f76b5df..f4c9658 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,107 +1,26 @@ GEM remote: http://rubygems.org/ specs: - addressable (2.5.0) - public_suffix (~> 2.0, >= 2.0.2) - bouncy-castle-java (1.5.0147) - builder (3.2.2) - descendants_tracker (0.0.4) - thread_safe (~> 0.3, >= 0.3.1) diff-lcs (1.2.5) - faraday (0.9.2) - multipart-post (>= 1.2, < 3) - ffi (1.9.14-java) - git (1.3.0) - github_api (0.11.3) - addressable (~> 2.3) - descendants_tracker (~> 0.0.1) - faraday (~> 0.8, < 0.10) - hashie (>= 1.2) - multi_json (>= 1.7.5, < 2.0) - nokogiri (~> 1.6.0) - oauth2 - hashie (3.4.6) - highline (1.7.8) - httpclient (2.8.2.4) - jeweler (2.1.2) - builder - bundler (>= 1.0) - git (>= 1.2.5) - github_api (~> 0.11.0) - highline (>= 1.6.15) - nokogiri (>= 1.5.10) - rake - rdoc - semver - jruby-openssl (0.9.4) - bouncy-castle-java (>= 1.5.0147) - json (1.8.3) - json (1.8.3-java) - jwt (1.5.6) - launchy (2.4.3) - addressable (~> 2.3) - launchy (2.4.3-java) - addressable (~> 2.3) - spoon (~> 0.0.1) - mini_portile2 (2.1.0) - multi_json (1.12.1) - multi_xml (0.5.5) - multipart-post (2.0.0) - nayutaya-msgpack-pure (0.0.2) - nokogiri (1.6.8.1) - mini_portile2 (~> 2.1.0) - nokogiri (1.6.8.1-java) - oauth2 (1.2.0) - faraday (>= 0.8, < 0.10) - jwt (~> 1.0) - multi_json (~> 1.3) - multi_xml (~> 0.5) - rack (>= 1.2, < 3) - public_suffix (2.0.3) - rack (2.0.1) - rake (11.3.0) - rdoc (4.2.2) - json (~> 1.4) rspec (3.5.0) rspec-core (~> 3.5.0) rspec-expectations (~> 3.5.0) rspec-mocks (~> 3.5.0) rspec-core (3.5.4) rspec-support (~> 3.5.0) rspec-expectations (3.5.0) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.5.0) rspec-mocks (3.5.0) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.5.0) rspec-support (3.5.0) - semver (1.0.1) - spoon (0.0.6) - ffi - tddium (1.25.5) - github_api - highline - json - launchy - nayutaya-msgpack-pure (~> 0.0.2) - tddium_client (~> 0.4.2) - thor - tddium_client (0.4.3) - httpclient (>= 2.2.5) - json - thor (0.19.1) - thread_safe (0.3.5) - thread_safe (0.3.5-java) PLATFORMS java - ruby DEPENDENCIES - jeweler (>= 1.8.4) - jruby-openssl - rspec (>= 2.11.0) - tddium + rspec (~> 3.0) BUNDLED WITH 1.13.6
kameeoze/jruby-poi
54f1eba97f0bb0738d760de4c920be5d42a10e4c
Travis.. manners... install bundler.
diff --git a/.travis.yml b/.travis.yml index 589e7c9..bd71939 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,14 @@ language: ruby os: - linux - osx rvm: - jruby-9.1.5.0 + +before_install: + - gem install bundler + +cache: + - bundler
kameeoze/jruby-poi
f2b74e7a754313f8c1087713ff06538a7e1013a0
Refocus to jruby 9+
diff --git a/.travis.yml b/.travis.yml index f8383ec..589e7c9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,8 @@ -language: ruby -rvm: - - jruby-18mode - - jruby-19mode \ No newline at end of file +language: ruby + +os: + - linux + - osx + +rvm: + - jruby-9.1.5.0
kameeoze/jruby-poi
0549556319ce74917627f1954f99a0245b8c6d29
issue fix #18 on jruby-9.x: NoMethodError: undefined method `row' for #<Java::OrgApachePoiXssfUsermodel::XSSFSheet:0x7f92d2df>
diff --git a/lib/poi/workbook/cell.rb b/lib/poi/workbook/cell.rb index f8cc56e..b755539 100644 --- a/lib/poi/workbook/cell.rb +++ b/lib/poi/workbook/cell.rb @@ -1,160 +1,160 @@ # -*- coding: utf-8 -*- require 'date' module POI class Cells include Enumerable def initialize(row) @row = row @poi_row = row.poi_row @cells = {} end def [](index) - @cells[index] ||= Cell.new(@poi_row.cell(index) || @poi_row.create_cell(index), @row) + @cells[index] ||= Cell.new(@poi_row.get_cell(index) || @poi_row.create_cell(index), @row) end def size @poi_row.physical_number_of_cells end def each it = @poi_row.cell_iterator yield Cell.new(it.next, @row) while it.has_next end end class Cell < Facade(:poi_cell, org.apache.poi.ss.usermodel.Cell) DATE_UTIL = Java::org.apache.poi.ss.usermodel.DateUtil CELL = Java::org.apache.poi.ss.usermodel.Cell CELL_VALUE = Java::org.apache.poi.ss.usermodel.CellValue CELL_TYPE_BLANK = CELL::CELL_TYPE_BLANK CELL_TYPE_BOOLEAN = CELL::CELL_TYPE_BOOLEAN CELL_TYPE_ERROR = CELL::CELL_TYPE_ERROR CELL_TYPE_FORMULA = CELL::CELL_TYPE_FORMULA CELL_TYPE_NUMERIC = CELL::CELL_TYPE_NUMERIC CELL_TYPE_STRING = CELL::CELL_TYPE_STRING def initialize(cell, row) @cell = cell @row = row end def <=> other return 1 if other.nil? return self.index <=> other.index end # This is NOT an inexpensive operation. The purpose of this method is merely to get more information # out of cell when one thinks the value returned is incorrect. It may have more value in development # than in production. def error_value if poi_cell.cell_type == CELL_TYPE_ERROR error_value_from(poi_cell.error_cell_value) elsif poi_cell.cell_type == CELL_TYPE_FORMULA && poi_cell.cached_formula_result_type == CELL_TYPE_ERROR cell_value = formula_evaluator.evaluate(poi_cell) cell_value && error_value_from(cell_value.error_value) else nil end end # returns the formula for this Cell if it has one, otherwise nil def formula_value poi_cell.cell_type == CELL_TYPE_FORMULA ? poi_cell.cell_formula : nil end def value return nil if poi_cell.nil? cast_value end def formula= new_value poi_cell.cell_formula = new_value @row.worksheet.workbook.on_formula_update self self end def formula poi_cell.cell_formula end def value= new_value set_cell_value new_value if new_value.nil? @row.worksheet.workbook.on_delete self else @row.worksheet.workbook.on_update self end self end def comment poi_cell.cell_comment end def index poi_cell.column_index end # Get the String representation of this Cell's value. # # If this Cell is a formula you can pass a false to this method and # get the formula instead of the String representation. def to_s(evaluate_formulas=true) return '' if poi_cell.nil? if poi_cell.cell_type == CELL_TYPE_FORMULA && evaluate_formulas == false formula_value else value.to_s end end # returns the underlying org.apache.poi.ss.usermodel.Cell def poi_cell @cell end # :cell_style= comes from the Façade superclass alias :style= :cell_style= def style! options self.style = @row.worksheet.workbook.create_style(options) end private def cast_value(type = cell_type) case type when CELL_TYPE_BLANK then nil when CELL_TYPE_BOOLEAN then get_boolean_cell_value when CELL_TYPE_ERROR then nil when CELL_TYPE_FORMULA then cast_value(poi_cell.cached_formula_result_type) when CELL_TYPE_STRING then get_string_cell_value when CELL_TYPE_NUMERIC if DATE_UTIL.cell_date_formatted(poi_cell) DateTime.parse(get_date_cell_value.to_s) else get_numeric_cell_value end else raise "unhandled cell type[#{type}]" end end def workbook @row.worksheet.workbook end def formula_evaluator workbook.formula_evaluator end def error_value_from(cell_value) - org.apache.poi.ss.usermodel.ErrorConstants.text(cell_value) + org.apache.poi.ss.usermodel.ErrorConstants.get_text(cell_value) end end end diff --git a/lib/poi/workbook/row.rb b/lib/poi/workbook/row.rb index 27feb8a..51e694a 100644 --- a/lib/poi/workbook/row.rb +++ b/lib/poi/workbook/row.rb @@ -1,58 +1,58 @@ module POI class Rows include Enumerable def initialize(worksheet) @worksheet = worksheet @poi_worksheet = worksheet.poi_worksheet @rows = {} end def [](index) - @rows[index] ||= Row.new(@poi_worksheet.row(index) || @poi_worksheet.create_row(index), @worksheet) + @rows[index] ||= Row.new(@poi_worksheet.get_row(index) || @poi_worksheet.create_row(index), @worksheet) end def size @poi_worksheet.physical_number_of_rows end def each it = @poi_worksheet.row_iterator yield Row.new(it.next, @worksheet) while it.has_next end end class Row < Facade(:poi_row, org.apache.poi.ss.usermodel.Row) def initialize(row, worksheet) @row = row @worksheet = worksheet end def [](index) return nil if poi_row.nil? cells[index] end def cells @cells ||= Cells.new(self) end def index return nil if poi_row.nil? poi_row.row_num end # def height_in_points= num # set_height_in_points num.to_f # end def poi_row @row end def worksheet @worksheet end end end diff --git a/lib/poi/workbook/workbook.rb b/lib/poi/workbook/workbook.rb index ad22f5a..350d301 100644 --- a/lib/poi/workbook/workbook.rb +++ b/lib/poi/workbook/workbook.rb @@ -1,268 +1,268 @@ require 'tmpdir' require 'stringio' require 'java' module POI class Workbook < Facade(:poi_workbook, org.apache.poi.ss.usermodel.Workbook) FONT = org.apache.poi.ss.usermodel.Font FONT_CONSTANTS = Hash[*FONT.constants.map{|e| [e.downcase.to_sym, FONT.const_get(e)]}.flatten] CELL_STYLE = org.apache.poi.ss.usermodel.CellStyle CELL_STYLE_CONSTANTS = Hash[*CELL_STYLE.constants.map{|e| [e.downcase.to_sym, CELL_STYLE.const_get(e)]}.flatten] INDEXED_COLORS = org.apache.poi.ss.usermodel.IndexedColors INDEXED_COLORS_CONSTANTS = Hash[*INDEXED_COLORS.constants.map{|e| [e.downcase.to_sym, INDEXED_COLORS.const_get(e)]}.flatten] def self.open(filename_or_stream) name, stream = if filename_or_stream.kind_of?(java.io.InputStream) [File.join(Dir.tmpdir, "spreadsheet.xlsx"), filename_or_stream] elsif filename_or_stream.kind_of?(IO) || StringIO === filename_or_stream || filename_or_stream.respond_to?(:read) # NOTE: the String.unpack here can be very inefficient on large files [File.join(Dir.tmpdir, "spreadsheet.xlsx"), java.io.ByteArrayInputStream.new(filename_or_stream.read.unpack('c*').to_java(:byte))] else raise Exception, "FileNotFound" unless File.exists?( filename_or_stream ) [filename_or_stream, java.io.FileInputStream.new(filename_or_stream)] end instance = self.new(name, stream) if block_given? result = yield instance return result end instance end def self.create(filename, options={}) self.new(filename, nil, options) end attr_reader :filename def initialize(filename, io_stream, options={}) @filename = filename @workbook = if io_stream org.apache.poi.ss.usermodel.WorkbookFactory.create(io_stream) elsif options[:format] == :hssf org.apache.poi.hssf.usermodel.HSSFWorkbook.new else org.apache.poi.xssf.usermodel.XSSFWorkbook.new end end def formula_evaluator @formula_evaluator ||= @workbook.creation_helper.create_formula_evaluator end def save save_as(@filename) end def save_as(filename) output = output_stream filename begin @workbook.write(output) ensure output.close end end def output_stream name java.io.FileOutputStream.new(name) end def close #noop end def create_sheet name='New Sheet' # @workbook.createSheet name worksheets[name] end def create_style options={} font = @workbook.createFont set_value( font, :font_height_in_points, options ) do | value | value.to_i end set_value font, :bold_weight, options, FONT_CONSTANTS set_value font, :color, options, INDEXED_COLORS_CONSTANTS do | value | value.index end style = @workbook.createCellStyle [:alignment, :vertical_alignment, :fill_pattern, :border_right, :border_left, :border_top, :border_bottom].each do | sym | set_value style, sym, options, CELL_STYLE_CONSTANTS do | value | value.to_i end end [:right_border_color, :left_border_color, :top_border_color, :bottom_border_color, :fill_foreground_color, :fill_background_color].each do | sym | set_value( style, sym, options, INDEXED_COLORS_CONSTANTS ) do | value | value.index end end [:hidden, :locked, :wrap_text].each do | sym | set_value style, sym, options end [:rotation, :indentation].each do | sym | set_value( style, sym, options ) do | value | value.to_i end end set_value( style, :data_format, options ) do |value| @workbook.create_data_format.getFormat(value) end style.font = font style end def set_value on, value_sym, from, using=nil return on unless from.has_key?(value_sym) value = if using using[from[value_sym]] else from[value_sym] end value = yield value if block_given? on.send("set_#{value_sym}", value) on end def worksheets @worksheets ||= Worksheets.new(self) end def named_ranges @named_ranges ||= ([email protected]_of_names).collect do | idx | - NamedRange.new @workbook.name_at(idx), self + NamedRange.new @workbook.get_name_at(idx), self end end # reference can be a Fixnum, referring to the 0-based sheet or # a String which is the sheet name or a cell reference. # # If a cell reference is passed the value of that cell is returned. # # If the reference refers to a contiguous range of cells an Array of values will be returned. # # If the reference refers to a multiple columns a Hash of values will be returned by column name. def [](reference) if Fixnum === reference return worksheets[reference] end if sheet = worksheets.detect{|e| e.name == reference} return sheet.poi_worksheet.nil? ? nil : sheet end cell = cell(reference) if Array === cell cell.collect{|e| e.value} elsif Hash === cell values = {} cell.each_pair{|column_name, cells| values[column_name] = cells.collect{|e| e.value}} values else cell.value end end # takes a String in the form of a 3D cell reference and returns the Cell (eg. "Sheet 1!A1") # # If the reference refers to a contiguous range of cells an array of Cells will be returned def cell reference # if the reference is to a named range of cells, get that range and return it if named_range = named_ranges.detect{|e| e.name == reference} cells = named_range.cells.compact if cells.empty? return nil else return cells.length == 1 ? cells.first : cells end end # check if the named_range is a full column reference if column_reference?(named_range) return all_cells_in_column named_range.formula end # if the reference is to an area of cells, get all the cells in that area and return them cells = cells_in_area(reference) unless cells.empty? return cells.length == 1 ? cells.first : cells end if column_reference?(reference) return all_cells_in_column reference end ref = POI::CELL_REF.new(reference) single_cell ref end # ref is a POI::CELL_REF instance def single_cell ref if ref.sheet_name.nil? raise 'cell references at the workbook level must include a sheet reference (eg. Sheet1!A1)' else worksheets[ref.sheet_name][ref.row][ref.col] end end def cells_in_area reference area = Area.new(reference) area.in(self) end def poi_workbook @workbook end def on_update cell #clear_all_formula_results #formula_evaluator.notify_update_cell cell.poi_cell end def on_formula_update cell #clear_all_formula_results formula_evaluator.notify_set_formula cell.poi_cell formula_evaluator.evaluate_formula_cell(cell.poi_cell) end def on_delete cell #clear_all_formula_results formula_evaluator.notify_delete_cell cell.poi_cell end def clear_all_formula_results formula_evaluator.clear_all_cached_result_values end def all_cells_in_column reference sheet_parts = reference.split('!') area_parts = sheet_parts.last.split(':') area_start = "#{sheet_parts.first}!#{area_parts.first}" area_end = area_parts.last area = org.apache.poi.ss.util.AreaReference.getWholeColumn(area_start, area_end) full_ref = "#{area.first_cell.format_as_string}:#{area.last_cell.format_as_string}" Area.new(full_ref).in(self) # cell_reference = org.apache.poi.ss.util.CellReference.new( reference + "1" ) # column = cell_reference.get_col # sheet = cell_reference.get_sheet_name # worksheets[sheet].rows.collect{|row| row[column]} end private def column_reference? named_range_or_reference return false if named_range_or_reference.nil? reference = named_range_or_reference if NamedRange === named_range_or_reference reference = named_range_or_reference.formula end cell_reference = reference.split('!', 2).last beginning, ending = cell_reference.split(':') !(beginning =~ /\d/ || (ending.nil? ? false : ending =~ /\d/)) end end end diff --git a/lib/poi/workbook/worksheet.rb b/lib/poi/workbook/worksheet.rb index 2732072..5c06fd1 100644 --- a/lib/poi/workbook/worksheet.rb +++ b/lib/poi/workbook/worksheet.rb @@ -1,78 +1,78 @@ module POI class Worksheets include Enumerable def initialize(workbook) @workbook = workbook @poi_workbook = workbook.poi_workbook end def [](index_or_name) worksheet = case when index_or_name.kind_of?(Numeric) - @poi_workbook.sheet_at(index_or_name) || @poi_workbook.create_sheet + @poi_workbook.get_sheet_at(index_or_name) || @poi_workbook.create_sheet else @poi_workbook.get_sheet(index_or_name) || @poi_workbook.create_sheet(index_or_name) end Worksheet.new(worksheet, @workbook) end def size @poi_workbook.number_of_sheets end def each - (0...size).each { |i| yield Worksheet.new(@poi_workbook.sheet_at(i), @workbook) } + (0...size).each { |i| yield Worksheet.new(@poi_workbook.get_sheet_at(i), @workbook) } end end class Worksheet < Facade(:poi_worksheet, org.apache.poi.ss.usermodel.Sheet) def initialize(worksheet, workbook) @worksheet = worksheet @workbook = workbook end def name @worksheet.sheet_name end def first_row @worksheet.first_row_num end def last_row @worksheet.last_row_num end def rows @rows ||= Rows.new(self) end # Accepts a Fixnum or a String as the row_index # # row_index as Fixnum: returns the 0-based row # # row_index as String: assumes a cell reference within this sheet # if the value of the reference is non-nil the value is returned, # otherwise the referenced cell is returned def [](row_index) if Fixnum === row_index rows[row_index] else ref = org.apache.poi.ss.util.CellReference.new(row_index) cell = rows[ref.row][ref.col] cell && cell.value ? cell.value : cell end end def poi_worksheet @worksheet end def workbook @workbook end end end
kameeoze/jruby-poi
ef8bf574d5ea161a9b70e582f2b3e8bc7a8ea89a
add GitHub Flavored Markdown to README
diff --git a/README.markdown b/README.markdown index 2088dc5..658d69d 100644 --- a/README.markdown +++ b/README.markdown @@ -1,91 +1,93 @@ [jruby-poi](http://github.com/kameeoze/jruby-poi) ========= [![Build Status](https://secure.travis-ci.org/kameeoze/jruby-poi.png)](http://travis-ci.org/kameeoze/jruby-poi) This little gem provides an alternative interface to the Apache POI java library, for JRuby. For now the API is targeted at wrapping spreadsheets. We may expand this in the future. INSTALL ======= -* gem install jruby-poi +``` +$ gem install jruby-poi +``` USAGE ===== -It's pretty simple really, create a POI::Workbook and access its sheets, rows, and cells. You can read from the spreadsheet, save it (as the filename with which you created or as a new spreadsheet via Workbook#save_as). - - require 'poi' - - # given an Excel spreadsheet whose first sheet (Sheet 1) has this data: - # A B C D E - # 1 4 A 2010-01-04 - # 2 3 B =DATE(YEAR($E$1), MONTH($E$1), A2) - # 3 2 C =DATE(YEAR($E$1), MONTH($E$1), A3) - # 4 1 D =DATE(YEAR($E$1), MONTH($E$1), A4) - - workbook = POI::Workbook.open('spreadsheet.xlsx') - sheet = workbook.worksheets["Sheet 1"] - rows = sheet.rows - - # get a cell's value -- returns the value as its proper type, evaluating formulas if need be - rows[0][0].value # => 4.0 - rows[0][1].value # => nil - rows[0][2].value # => 'A' - rows[0][3].value # => nil - rows[0][4].value # => 2010-01-04 as a Date instance - rows[1][4].value # => 2010-01-03 as a Date instance - rows[2][4].value # => 2010-01-02 as a Date instance - rows[3][4].value # => 2010-01-01 as a Date instance - - # you can access a cell in array style as well... these snippets are all equivalent - workbook.sheets[0][2][2] # => 'C' - workbook[0][2][2] # => 'C' - workbook.sheets['Sheet 1'][2][2] # => 'C' - workbook['Sheet 1'][2][2] # => 'C' - - # you can access a cell in 3D cell format too - workbook['Sheet 1!A1'] # => 4.0 - - # you can even refer to ranges of cells - workbook['Sheet 1!A1:A3'] # => [4.0, 3.0, 2.0] - - # if cells E1 - E4 were a named range, you could refer to those cells by its name - # eg. if the cells were named "dates"... - workbook['dates'] # => dates from E1 - E4 - - # to get the Cell instance, instead of its value, just use the Workbook#cell method - workbook.cell('dates') # => cells that contain dates from E1 to E4 - workbook['Sheet 1!A1:A3'] # => cells that contain 4.0, 3.0, and 2.0 - -There's a formatted version of this code [here](http://gist.github.com/557607), but Github doesn't allow embedding script tags in Markdown. Go figure! +It's pretty simple really, create an instance of `POI::Workbook` and access its sheets, rows, and cells. You can read from the spreadsheet, save it (as the filename with which you created or as a new spreadsheet via `Workbook#save_as`). + +```ruby +require 'poi' + +# given an Excel spreadsheet whose first sheet (Sheet 1) has this data: +# A B C D E +# 1 4 A 2010-01-04 +# 2 3 B =DATE(YEAR($E$1), MONTH($E$1), A2) +# 3 2 C =DATE(YEAR($E$1), MONTH($E$1), A3) +# 4 1 D =DATE(YEAR($E$1), MONTH($E$1), A4) + +workbook = POI::Workbook.open('spreadsheet.xlsx') +sheet = workbook.worksheets["Sheet 1"] +rows = sheet.rows + +# get a cell's value -- returns the value as its proper type, evaluating formulas if need be +rows[0][0].value # => 4.0 +rows[0][1].value # => nil +rows[0][2].value # => 'A' +rows[0][3].value # => nil +rows[0][4].value # => 2010-01-04 as a Date instance +rows[1][4].value # => 2010-01-03 as a Date instance +rows[2][4].value # => 2010-01-02 as a Date instance +rows[3][4].value # => 2010-01-01 as a Date instance + +# you can access a cell in array style as well... these snippets are all equivalent +workbook.sheets[0][2][2] # => 'C' +workbook[0][2][2] # => 'C' +workbook.sheets['Sheet 1'][2][2] # => 'C' +workbook['Sheet 1'][2][2] # => 'C' + +# you can access a cell in 3D cell format too +workbook['Sheet 1!A1'] # => 4.0 + +# you can even refer to ranges of cells +workbook['Sheet 1!A1:A3'] # => [4.0, 3.0, 2.0] + +# if cells E1 - E4 were a named range, you could refer to those cells by its name +# eg. if the cells were named "dates"... +workbook['dates'] # => dates from E1 - E4 + +# to get the Cell instance, instead of its value, just use the Workbook#cell method +workbook.cell('dates') # => cells that contain dates from E1 to E4 +workbook['Sheet 1!A1:A3'] # => cells that contain 4.0, 3.0, and 2.0 +``` TODO ==== * fix reading ODS files -- we have a broken spec for this in io_spec.rb * add APIs for updating cells in a spreadsheet * create API for non-spreadsheet files * rdocs * tutorials, and/or better samples Contributors ============ * [Scott Deming](http://github.com/sdeming) * [Jason Rogers](http://github.com/jacaetevha) Note on Patches/Pull Requests ============================= * Fork the project. * Make your feature addition or bug fix. * Add tests for it. This is important so I don't break it in a future version unintentionally. * Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull) * Send me a pull request. Copyright ========= Copyright (c) 2010 Scott Deming and others. See NOTICE and LICENSE for details.
kameeoze/jruby-poi
c0d68ff32c9d19fa28d44d0a9f0fd3f3c6c07314
upgrade to POI 3.10
diff --git a/jruby-poi.gemspec b/jruby-poi.gemspec index a0f241e..e2d90ae 100644 --- a/jruby-poi.gemspec +++ b/jruby-poi.gemspec @@ -1,85 +1,85 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "jruby-poi" s.version = "0.9.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Scott Deming", "Jason Rogers"] s.date = "2012-10-15" s.description = "A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI." s.email = ["[email protected]", "[email protected]"] s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ ".travis.yml", "Gemfile", "Gemfile.lock", "LICENSE", "NOTICE", "README.markdown", "Rakefile", "VERSION", "jruby-poi.gemspec", "lib/ooxml-lib/dom4j-1.6.1.jar", "lib/ooxml-lib/stax-api-1.0.1.jar", "lib/ooxml-lib/xmlbeans-2.3.0.jar", - "lib/poi-3.8-20120326.jar", - "lib/poi-examples-3.8-20120326.jar", - "lib/poi-excelant-3.8-20120326.jar", - "lib/poi-ooxml-3.8-20120326.jar", - "lib/poi-ooxml-schemas-3.8-20120326.jar", - "lib/poi-scratchpad-3.8-20120326.jar", + "lib/poi-3.10.1-20140818.jar", + "lib/poi-examples-3.10.1-20140818.jar", + "lib/poi-excelant-3.10.1-20140818.jar", + "lib/poi-ooxml-3.10.1-20140818.jar", + "lib/poi-ooxml-schemas-3.10.1-20140818.jar", + "lib/poi-scratchpad-3.10.1-20140818.jar", "lib/poi.rb", "lib/poi/workbook.rb", "lib/poi/workbook/area.rb", "lib/poi/workbook/cell.rb", "lib/poi/workbook/named_range.rb", "lib/poi/workbook/row.rb", "lib/poi/workbook/workbook.rb", "lib/poi/workbook/worksheet.rb", "spec/data/simple_with_picture.ods", "spec/data/simple_with_picture.xls", "spec/data/spreadsheet.ods", "spec/data/timesheet.xlsx", "spec/data/various_samples.xlsx", "spec/facade_spec.rb", "spec/io_spec.rb", "spec/spec_helper.rb", "spec/support/java/jrubypoi/MockOutputStream.java", "spec/support/java/support.jar", "spec/support/matchers/cell_matcher.rb", "spec/workbook_spec.rb", "spec/writing_spec.rb", "spec_debug.sh" ] s.homepage = "http://github.com/kameeoze/jruby-poi" s.licenses = ["Apache"] s.require_paths = ["lib"] s.rubygems_version = "1.8.24" s.summary = "Apache POI class library for jruby" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, [">= 2.11.0"]) s.add_development_dependency(%q<jeweler>, [">= 1.8.4"]) s.add_development_dependency(%q<jruby-openssl>, [">= 0"]) else s.add_dependency(%q<rspec>, [">= 2.11.0"]) s.add_dependency(%q<jeweler>, [">= 1.8.4"]) s.add_dependency(%q<jruby-openssl>, [">= 0"]) end else s.add_dependency(%q<rspec>, [">= 2.11.0"]) s.add_dependency(%q<jeweler>, [">= 1.8.4"]) s.add_dependency(%q<jruby-openssl>, [">= 0"]) end end diff --git a/lib/ooxml-lib/xmlbeans-2.3.0.jar b/lib/ooxml-lib/xmlbeans-2.6.0.jar similarity index 55% rename from lib/ooxml-lib/xmlbeans-2.3.0.jar rename to lib/ooxml-lib/xmlbeans-2.6.0.jar index ccd8163..d1b6627 100644 Binary files a/lib/ooxml-lib/xmlbeans-2.3.0.jar and b/lib/ooxml-lib/xmlbeans-2.6.0.jar differ diff --git a/lib/poi-3.8-20120326.jar b/lib/poi-3.10.1-20140818.jar similarity index 50% rename from lib/poi-3.8-20120326.jar rename to lib/poi-3.10.1-20140818.jar index edc0ee5..dd1ab4a 100644 Binary files a/lib/poi-3.8-20120326.jar and b/lib/poi-3.10.1-20140818.jar differ diff --git a/lib/poi-examples-3.8-20120326.jar b/lib/poi-examples-3.10.1-20140818.jar similarity index 78% rename from lib/poi-examples-3.8-20120326.jar rename to lib/poi-examples-3.10.1-20140818.jar index 1c3351a..4985833 100644 Binary files a/lib/poi-examples-3.8-20120326.jar and b/lib/poi-examples-3.10.1-20140818.jar differ diff --git a/lib/poi-excelant-3.10.1-20140818.jar b/lib/poi-excelant-3.10.1-20140818.jar new file mode 100644 index 0000000..666ede0 Binary files /dev/null and b/lib/poi-excelant-3.10.1-20140818.jar differ diff --git a/lib/poi-excelant-3.8-20120326.jar b/lib/poi-excelant-3.8-20120326.jar deleted file mode 100644 index ad39033..0000000 Binary files a/lib/poi-excelant-3.8-20120326.jar and /dev/null differ diff --git a/lib/poi-ooxml-3.10.1-20140818.jar b/lib/poi-ooxml-3.10.1-20140818.jar new file mode 100644 index 0000000..fab0eea Binary files /dev/null and b/lib/poi-ooxml-3.10.1-20140818.jar differ diff --git a/lib/poi-ooxml-3.8-20120326.jar b/lib/poi-ooxml-3.8-20120326.jar deleted file mode 100644 index 9175c16..0000000 Binary files a/lib/poi-ooxml-3.8-20120326.jar and /dev/null differ diff --git a/lib/poi-ooxml-schemas-3.8-20120326.jar b/lib/poi-ooxml-schemas-3.10.1-20140818.jar similarity index 77% rename from lib/poi-ooxml-schemas-3.8-20120326.jar rename to lib/poi-ooxml-schemas-3.10.1-20140818.jar index 2372d1e..f8602b5 100644 Binary files a/lib/poi-ooxml-schemas-3.8-20120326.jar and b/lib/poi-ooxml-schemas-3.10.1-20140818.jar differ diff --git a/lib/poi-scratchpad-3.8-20120326.jar b/lib/poi-scratchpad-3.10.1-20140818.jar similarity index 53% rename from lib/poi-scratchpad-3.8-20120326.jar rename to lib/poi-scratchpad-3.10.1-20140818.jar index 02e52e8..61ec79f 100644 Binary files a/lib/poi-scratchpad-3.8-20120326.jar and b/lib/poi-scratchpad-3.10.1-20140818.jar differ diff --git a/lib/poi.rb b/lib/poi.rb index b42d20f..1734837 100644 --- a/lib/poi.rb +++ b/lib/poi.rb @@ -1,15 +1,15 @@ JRUBY_POI_LIB_PATH=File.expand_path(File.dirname(__FILE__)) # Java require 'java' -require File.join(JRUBY_POI_LIB_PATH, 'poi-3.8-20120326.jar') -require File.join(JRUBY_POI_LIB_PATH, 'poi-ooxml-3.8-20120326.jar') -require File.join(JRUBY_POI_LIB_PATH, 'poi-ooxml-schemas-3.8-20120326.jar') -require File.join(JRUBY_POI_LIB_PATH, 'poi-scratchpad-3.8-20120326.jar') -require File.join(JRUBY_POI_LIB_PATH, 'ooxml-lib', 'xmlbeans-2.3.0.jar') +require File.join(JRUBY_POI_LIB_PATH, 'poi-3.10.1-20140818.jar') +require File.join(JRUBY_POI_LIB_PATH, 'poi-ooxml-3.10.1-20140818.jar') +require File.join(JRUBY_POI_LIB_PATH, 'poi-ooxml-schemas-3.10.1-20140818.jar') +require File.join(JRUBY_POI_LIB_PATH, 'poi-scratchpad-3.10.1-20140818.jar') +require File.join(JRUBY_POI_LIB_PATH, 'ooxml-lib', 'xmlbeans-2.6.0.jar') require File.join(JRUBY_POI_LIB_PATH, 'ooxml-lib', 'dom4j-1.6.1.jar') require File.join(JRUBY_POI_LIB_PATH, 'ooxml-lib', 'stax-api-1.0.1.jar') # Ruby require File.join(JRUBY_POI_LIB_PATH, 'poi', 'workbook') require 'date' # required for Date.parse diff --git a/lib/poi/workbook/area.rb b/lib/poi/workbook/area.rb index e38f3b1..0013bf1 100644 --- a/lib/poi/workbook/area.rb +++ b/lib/poi/workbook/area.rb @@ -1,81 +1,83 @@ module POI class Area def initialize reference @ref = reference end - + def in workbook if single_cell_reference? ref = area.all_referenced_cells.first return [workbook.single_cell(ref)] end - + begin by_column = {} # refs = area.all_referenced_cells # slices = refs.enum_slice(refs.length/15) # slices.collect do |cell_refs| # Thread.start do # cell_refs.each do |cell_ref| # first = workbook.worksheets[cell_ref.sheet_name].first_row # last = workbook.worksheets[cell_ref.sheet_name].last_row # next unless cell_ref.row >= first && cell_ref.row <= last - # + # # # ref = POI::CELL_REF.new(c.format_as_string) # cell = workbook.single_cell cell_ref # (by_column[cell_ref.cell_ref_parts.collect.last] ||= []) << cell # end # end # end.each {|t| t.join} area.all_referenced_cells.each do |cell_ref| first = workbook.worksheets[cell_ref.sheet_name].first_row last = workbook.worksheets[cell_ref.sheet_name].last_row next unless cell_ref.row >= first && cell_ref.row <= last - + # ref = POI::CELL_REF.new(c.format_as_string) cell = workbook.single_cell cell_ref (by_column[cell_ref.cell_ref_parts.to_a.last] ||= []) << cell end - + by_column.each do |key, cells| by_column[key] = cells.compact end - + if by_column.length == 1 by_column.values.flatten else by_column end rescue [] end end - + def single_cell_reference? area.single_cell? #@ref == getFirstCell.formatAsString rescue false end - + private def area @area ||= new_area_reference end - + def new_area_reference begin + return column_reference + rescue return POI::AREA_REF.new(@ref) rescue - # not a valid reference, so proceed through to see if it's a column-based reference + raise "could not determine area reference for #{@ref}: #{$!.message}" end + end + + def column_reference sheet_parts = @ref.split('!') area_parts = sheet_parts.last.split(':') area_start = "#{sheet_parts.first}!#{area_parts.first}" area_end = area_parts.last - begin - POI::AREA_REF.getWholeColumn(area_start, area_end) - rescue - raise "could not determine area reference for #{@ref}: #{$!.message}" - end + + POI::AREA_REF.getWholeColumn(area_start, area_end) end end end diff --git a/spec/data/various_samples.xlsx b/spec/data/various_samples.xlsx index ec5d456..f50c3ad 100644 Binary files a/spec/data/various_samples.xlsx and b/spec/data/various_samples.xlsx differ diff --git a/spec/workbook_spec.rb b/spec/workbook_spec.rb index fa98d05..382c18c 100644 --- a/spec/workbook_spec.rb +++ b/spec/workbook_spec.rb @@ -1,369 +1,373 @@ require 'spec_helper' require 'date' require 'stringio' VARIOUS_SAMPLES_PATH = TestDataFile.expand_path("various_samples.xlsx") DATES_1904_WINDOW_XLS_PATH = TestDataFile.expand_path("1904_window_dates.xls") describe POI::Workbook do it "should open a workbook and allow access to its worksheets" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) - book.worksheets.size.should == 5 + book.worksheets.size.should == 6 book.filename.should == VARIOUS_SAMPLES_PATH end it "should be able to create a Workbook from an IO object" do content = StringIO.new(open(VARIOUS_SAMPLES_PATH, 'rb'){|f| f.read}) book = POI::Workbook.open(content) - book.worksheets.size.should == 5 + book.worksheets.size.should == 6 book.filename.should =~ /spreadsheet.xlsx$/ end it "should be able to create a Workbook from a Java input stream" do content = java.io.FileInputStream.new(VARIOUS_SAMPLES_PATH) book = POI::Workbook.open(content) - book.worksheets.size.should == 5 + book.worksheets.size.should == 6 book.filename.should =~ /spreadsheet.xlsx$/ end it "should create an HSSFWorkbook when passed a :format => :hssf option" do book = POI::Workbook.create('test.xls', :format => :hssf) book.poi_workbook.should be_kind_of(org.apache.poi.hssf.usermodel.HSSFWorkbook) end it "should create an XSSFWorkbook when passed a :format => :xssf option" do book = POI::Workbook.create('test.xlsx', :format => :xssf) book.poi_workbook.should be_kind_of(org.apache.poi.xssf.usermodel.XSSFWorkbook) end it "should create an XSSFWorkbook by default" do book = POI::Workbook.create('test.xlsx') book.poi_workbook.should be_kind_of(org.apache.poi.xssf.usermodel.XSSFWorkbook) end it "should return a column of cells by reference" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book["numbers!$A"].should == book['numbers'].rows.collect{|e| e[0].value} book["numbers!A"].should == book['numbers'].rows.collect{|e| e[0].value} book["numbers!C"].should == book['numbers'].rows.collect{|e| e[2].value} book["numbers!$D:$D"].should == book['numbers'].rows.collect{|e| e[3].value} book["numbers!$c:$D"].should == {"C" => book['numbers'].rows.collect{|e| e[2].value}, "D" => book['numbers'].rows.collect{|e| e[3].value}} end - + it "should return cells by reference" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book.cell("numbers!A1").value.should == 'NUM' book.cell("numbers!A2").to_s.should == '1.0' book.cell("numbers!A3").to_s.should == '2.0' book.cell("numbers!A4").to_s.should == '3.0' - + book.cell("numbers!A10").to_s.should == '9.0' book.cell("numbers!B10").to_s.should == '81.0' book.cell("numbers!C10").to_s.should == '729.0' book.cell("numbers!D10").to_s.should == '3.0' book.cell("text & pic!A10").value.should == 'This is an Excel XLSX workbook.' book.cell("bools & errors!B3").value.should == true book.cell("high refs!AM619").value.should == 'This is some text' book.cell("high refs!AO624").value.should == 24.0 book.cell("high refs!AP631").value.should == 13.0 book.cell(%Q{'text & pic'!A10}).value.should == 'This is an Excel XLSX workbook.' book.cell(%Q{'bools & errors'!B3}).value.should == true book.cell(%Q{'high refs'!AM619}).value.should == 'This is some text' book.cell(%Q{'high refs'!AO624}).value.should == 24.0 book.cell(%Q{'high refs'!AP631}).value.should == 13.0 end - + it "should handle named cell ranges" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book.named_ranges.length.should == 3 book.named_ranges.collect{|e| e.name}.should == %w{four_times_six NAMES nums} book.named_ranges.collect{|e| e.sheet.name}.should == ['high refs', 'bools & errors', 'high refs'] book.named_ranges.collect{|e| e.formula}.should == ["'high refs'!$AO$624", "'bools & errors'!$D$2:$D$11", "'high refs'!$AP$619:$AP$631"] book['four_times_six'].should == 24.0 book['nums'].should == (1..13).collect{|e| e * 1.0} - + # NAMES is a range of empty cells book['NAMES'].should == [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil] book.cell('NAMES').each do | cell | cell.value.should be_nil cell.poi_cell.should_not be_nil cell.to_s.should be_empty end end - + it "should return an array of cell values by reference" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book['dates!A2:A16'].map(&:to_date).should == (Date.parse('2010-02-28')..Date.parse('2010-03-14')).to_a end - + it "should return cell values by reference" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book['text & pic!A10'].should == 'This is an Excel XLSX workbook.' book['bools & errors!B3'].should == true book['high refs!AM619'].should == 'This is some text' book['high refs!AO624'].should == 24.0 book['high refs!AP631'].should == 13.0 end end describe POI::Worksheets do let(:book) { POI::Workbook.open(VARIOUS_SAMPLES_PATH) } it "should allow indexing worksheets by ordinal" do book.worksheets[0].name.should == "text & pic" book.worksheets[1].name.should == "numbers" book.worksheets[2].name.should == "dates" book.worksheets[3].name.should == "bools & errors" end it "should allow indexing worksheets by name" do book.worksheets["text & pic"].name.should == "text & pic" book.worksheets["numbers"].name.should == "numbers" book.worksheets["dates"].name.should == "dates" end it "should be enumerable" do book.worksheets.should be_kind_of Enumerable book.worksheets.each do |sheet| sheet.should be_kind_of POI::Worksheet end - book.worksheets.count.should == 5 - book.worksheets.collect.count.should == 5 + book.worksheets.count.should == 6 + book.worksheets.collect.count.should == 6 end - + it "returns cells when passing a cell reference" do book['dates']['A2'].class.should == DateTime book['dates']['A2'].to_date.should == Date.parse('2010-02-28') book['dates']['a2'].to_date.should == Date.parse('2010-02-28') book['dates']['B2'].to_date.should == Date.parse('2010-03-14') book['dates']['b2'].to_date.should == Date.parse('2010-03-14') book['dates']['C2'].to_date.should == Date.parse('2010-03-28') book['dates']['c2'].to_date.should == Date.parse('2010-03-28') end end describe POI::Rows do it "should be enumerable" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) sheet = book.worksheets["text & pic"] sheet.rows.should be_kind_of Enumerable - + sheet.rows.each do |row| row.should be_kind_of POI::Row end sheet.rows.count.should == 7 sheet.rows.collect.count.should == 7 end end describe POI::Cells do let(:book) { POI::Workbook.open(VARIOUS_SAMPLES_PATH) } it "should be enumerable" do sheet = book.worksheets["text & pic"] rows = sheet.rows cells = rows[0].cells cells.should be_kind_of Enumerable cells.count.should == 1 cells.collect.count.should == 1 end end describe POI::Cell do let(:book) { POI::Workbook.open(VARIOUS_SAMPLES_PATH) } context "1900 windowed dates" do it "should provide dates for date cells" do sheet = book.worksheets["dates"] rows = sheet.rows dates_by_column = [ (DateTime.parse('2010-02-28')..DateTime.parse('2010-03-14')), (DateTime.parse('2010-03-14')..DateTime.parse('2010-03-28')), (DateTime.parse('2010-03-28')..DateTime.parse('2010-04-11')) ] (0..2).each do |col| dates_by_column[col].each_with_index do |date, index| row = index + 1 c = sheet.rows[row].cells[col] c.value.to_date.should == date.to_date end end end end context "1904 windowed dates" do let(:book) { POI::Workbook.open(DATES_1904_WINDOW_XLS_PATH) } it "returns entered dates correctly" do c = book.worksheets[0].rows[1].cells[0] c.value.to_date.should == Date.parse("2012-01-01") end it "returns dates computed by a formula correctly" do c = book.worksheets[0].rows[1].cells[3] c.value.to_date.should == Date.parse("2012-01-02") end end it "should provide numbers for numeric cells" do sheet = book.worksheets["numbers"] rows = sheet.rows - + (1..15).each do |number| row = number rows[row][0].value.should equal_at_cell(number, row, 0) rows[row][1].value.should equal_at_cell(number ** 2, row, 1) rows[row][2].value.should equal_at_cell(number ** 3, row, 2) rows[row][3].value.should equal_at_cell(Math.sqrt(number), row, 3) end - + rows[9][0].to_s.should == '9.0' rows[9][1].to_s.should == '81.0' rows[9][2].to_s.should == '729.0' rows[9][3].to_s.should == '3.0' end it "should handle array access from the workbook down to cells" do book[1][9][0].to_s.should == '9.0' book[1][9][1].to_s.should == '81.0' book[1][9][2].to_s.should == '729.0' book[1][9][3].to_s.should == '3.0' book["numbers"][9][0].to_s.should == '9.0' book["numbers"][9][1].to_s.should == '81.0' book["numbers"][9][2].to_s.should == '729.0' book["numbers"][9][3].to_s.should == '3.0' end it "should provide error text for error cells" do sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[6][0].value.should == 0.0 #'~CIRCULAR~REF~' rows[6][0].error_value.should be_nil rows[7][0].value.should be_nil rows[7][0].error_value.should == '#DIV/0!' rows[8][0].value.should be_nil rows[8][0].error_value.should == '#N/A' rows[9][0].value.should be_nil rows[9][0].error_value.should == '#NAME?' rows[10][0].value.should be_nil rows[10][0].error_value.should == '#NULL!' rows[11][0].value.should be_nil rows[11][0].error_value.should == '#NUM!' rows[12][0].value.should be_nil rows[12][0].error_value.should == '#REF!' rows[13][0].value.should be_nil rows[13][0].error_value.should == '#VALUE!' lambda{ rows[14][0].value }.should_not raise_error(Java::java.lang.RuntimeException) - + rows[6][0].to_s.should == '0.0' #'~CIRCULAR~REF~' rows[7][0].to_s.should == '' #'#DIV/0!' rows[8][0].to_s.should == '' #'#N/A' rows[9][0].to_s.should == '' #'#NAME?' rows[10][0].to_s.should == '' #'#NULL!' rows[11][0].to_s.should == '' #'#NUM!' rows[12][0].to_s.should == '' #'#REF!' rows[13][0].to_s.should == '' #'#VALUE!' rows[14][0].to_s.should == '' end it "should provide booleans for boolean cells" do sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[1][0].value.should == false rows[1][0].to_s.should == 'false' - + rows[1][1].value.should == false rows[1][1].to_s.should == 'false' - + rows[2][0].value.should == true rows[2][0].to_s.should == 'true' - + rows[2][1].value.should == true rows[2][1].to_s.should == 'true' end it "should provide the cell value as a string" do sheet = book.worksheets["text & pic"] rows = sheet.rows rows[0][0].value.should == "This" rows[1][0].value.should == "is" rows[2][0].value.should == "an" rows[3][0].value.should == "Excel" rows[4][0].value.should == "XLSX" rows[5][0].value.should == "workbook" rows[9][0].value.should == 'This is an Excel XLSX workbook.' - + rows[0][0].to_s.should == "This" rows[1][0].to_s.should == "is" rows[2][0].to_s.should == "an" rows[3][0].to_s.should == "Excel" rows[4][0].to_s.should == "XLSX" rows[5][0].to_s.should == "workbook" rows[9][0].to_s.should == 'This is an Excel XLSX workbook.' end - + it "should provide formulas instead of string-ified values" do sheet = book.worksheets["numbers"] rows = sheet.rows (1..15).each do |number| row = number rows[row][0].to_s(false).should == "#{number}.0" rows[row][1].to_s(false).should == "A#{row + 1}*A#{row + 1}" rows[row][2].to_s(false).should == "B#{row + 1}*A#{row + 1}" rows[row][3].to_s(false).should == "SQRT(A#{row + 1})" end sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[1][0].to_s(false).should == '1=2' rows[1][1].to_s(false).should == 'FALSE' rows[2][0].to_s(false).should == '1=1' rows[2][1].to_s(false).should == 'TRUE' rows[14][0].to_s(false).should == 'foobar(1)' - + sheet = book.worksheets["text & pic"] sheet.rows[9][0].to_s(false).should == 'CONCATENATE(A1," ", A2," ", A3," ", A4," ", A5," ", A6,".")' end - + it "should handle getting values out of 'non-existent' cells" do sheet = book.worksheets["bools & errors"] sheet.rows[14][2].value.should be_nil end it "should notify the workbook that I have been updated" do book['dates!A10'].to_date.should == Date.parse('2010-03-08') book['dates!A16'].to_date.should == Date.parse('2010-03-14') book['dates!B2'].to_date.should == Date.parse('2010-03-14') cell = book.cell('dates!B2') cell.formula.should == 'A16' - + cell.formula = 'A10 + 1' book.cell('dates!B2').poi_cell.should === cell.poi_cell book.cell('dates!B2').formula.should == 'A10 + 1' book['dates!B2'].to_date.should == Date.parse('2010-03-09') end + + it "should work with IFERROR" do + book['newfeatures!F6'].should == 'NOT FOUND' + end end
kameeoze/jruby-poi
4b24ec08006c8313593d81bd73a30fb5091721b4
Add DateTime::to_date to spec_helper for ruby 1.8
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 2c1c18c..738d741 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,16 +1,25 @@ require 'spec_helper' RSpec.configure do |c| c.filter_run_excluding :unimplemented => true end require File.expand_path('../lib/poi', File.dirname(__FILE__)) Dir[File.dirname(__FILE__) + "/support/**/*.rb"].each {|f| require f} require File.join(File.dirname(__FILE__), "support", "java", "support.jar") class TestDataFile def self.expand_path(name) File.expand_path(File.join(File.dirname(__FILE__), 'data', name)) end end + +if RUBY_VERSION < '1.9' + class DateTime + def to_date + Date.parse(self.strftime('%Y-%m-%d')) + end + end +end +
kameeoze/jruby-poi
04b5f2cc90115c0a42c337fdf3dbf07845b51ed5
Fixed failing Date tests. Should be using DateTime. Dates read from worksheet take on local timezone offset which doesn't seem right. Will have to revisit.
diff --git a/spec/support/matchers/cell_matcher.rb b/spec/support/matchers/cell_matcher.rb index 3b90c8b..1b245a5 100644 --- a/spec/support/matchers/cell_matcher.rb +++ b/spec/support/matchers/cell_matcher.rb @@ -1,17 +1,17 @@ RSpec::Matchers.define :equal_at_cell do |expected, row, col| match do |actual| actual == expected end failure_message_for_should do |actual| "expected #{actual} to equal #{expected} (row:#{row}, cell:#{col})" end failure_message_for_should_not do |actual| "expected #{actual} not to equal #{expected} (row:#{row}, cell:#{col})" end description do "to equal #{expected}" end -end \ No newline at end of file +end diff --git a/spec/workbook_spec.rb b/spec/workbook_spec.rb index 7a267d5..fa98d05 100644 --- a/spec/workbook_spec.rb +++ b/spec/workbook_spec.rb @@ -1,366 +1,369 @@ require 'spec_helper' require 'date' require 'stringio' VARIOUS_SAMPLES_PATH = TestDataFile.expand_path("various_samples.xlsx") DATES_1904_WINDOW_XLS_PATH = TestDataFile.expand_path("1904_window_dates.xls") describe POI::Workbook do it "should open a workbook and allow access to its worksheets" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book.worksheets.size.should == 5 book.filename.should == VARIOUS_SAMPLES_PATH end it "should be able to create a Workbook from an IO object" do content = StringIO.new(open(VARIOUS_SAMPLES_PATH, 'rb'){|f| f.read}) book = POI::Workbook.open(content) book.worksheets.size.should == 5 book.filename.should =~ /spreadsheet.xlsx$/ end it "should be able to create a Workbook from a Java input stream" do content = java.io.FileInputStream.new(VARIOUS_SAMPLES_PATH) book = POI::Workbook.open(content) book.worksheets.size.should == 5 book.filename.should =~ /spreadsheet.xlsx$/ end it "should create an HSSFWorkbook when passed a :format => :hssf option" do book = POI::Workbook.create('test.xls', :format => :hssf) book.poi_workbook.should be_kind_of(org.apache.poi.hssf.usermodel.HSSFWorkbook) end it "should create an XSSFWorkbook when passed a :format => :xssf option" do book = POI::Workbook.create('test.xlsx', :format => :xssf) book.poi_workbook.should be_kind_of(org.apache.poi.xssf.usermodel.XSSFWorkbook) end it "should create an XSSFWorkbook by default" do book = POI::Workbook.create('test.xlsx') book.poi_workbook.should be_kind_of(org.apache.poi.xssf.usermodel.XSSFWorkbook) end it "should return a column of cells by reference" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book["numbers!$A"].should == book['numbers'].rows.collect{|e| e[0].value} book["numbers!A"].should == book['numbers'].rows.collect{|e| e[0].value} book["numbers!C"].should == book['numbers'].rows.collect{|e| e[2].value} book["numbers!$D:$D"].should == book['numbers'].rows.collect{|e| e[3].value} book["numbers!$c:$D"].should == {"C" => book['numbers'].rows.collect{|e| e[2].value}, "D" => book['numbers'].rows.collect{|e| e[3].value}} end it "should return cells by reference" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book.cell("numbers!A1").value.should == 'NUM' book.cell("numbers!A2").to_s.should == '1.0' book.cell("numbers!A3").to_s.should == '2.0' book.cell("numbers!A4").to_s.should == '3.0' book.cell("numbers!A10").to_s.should == '9.0' book.cell("numbers!B10").to_s.should == '81.0' book.cell("numbers!C10").to_s.should == '729.0' book.cell("numbers!D10").to_s.should == '3.0' book.cell("text & pic!A10").value.should == 'This is an Excel XLSX workbook.' book.cell("bools & errors!B3").value.should == true book.cell("high refs!AM619").value.should == 'This is some text' book.cell("high refs!AO624").value.should == 24.0 book.cell("high refs!AP631").value.should == 13.0 book.cell(%Q{'text & pic'!A10}).value.should == 'This is an Excel XLSX workbook.' book.cell(%Q{'bools & errors'!B3}).value.should == true book.cell(%Q{'high refs'!AM619}).value.should == 'This is some text' book.cell(%Q{'high refs'!AO624}).value.should == 24.0 book.cell(%Q{'high refs'!AP631}).value.should == 13.0 end it "should handle named cell ranges" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book.named_ranges.length.should == 3 book.named_ranges.collect{|e| e.name}.should == %w{four_times_six NAMES nums} book.named_ranges.collect{|e| e.sheet.name}.should == ['high refs', 'bools & errors', 'high refs'] book.named_ranges.collect{|e| e.formula}.should == ["'high refs'!$AO$624", "'bools & errors'!$D$2:$D$11", "'high refs'!$AP$619:$AP$631"] book['four_times_six'].should == 24.0 book['nums'].should == (1..13).collect{|e| e * 1.0} # NAMES is a range of empty cells book['NAMES'].should == [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil] book.cell('NAMES').each do | cell | cell.value.should be_nil cell.poi_cell.should_not be_nil cell.to_s.should be_empty end end it "should return an array of cell values by reference" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) - book['dates!A2:A16'].should == (Date.parse('2010-02-28')..Date.parse('2010-03-14')).to_a + book['dates!A2:A16'].map(&:to_date).should == (Date.parse('2010-02-28')..Date.parse('2010-03-14')).to_a end it "should return cell values by reference" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book['text & pic!A10'].should == 'This is an Excel XLSX workbook.' book['bools & errors!B3'].should == true book['high refs!AM619'].should == 'This is some text' book['high refs!AO624'].should == 24.0 book['high refs!AP631'].should == 13.0 end end describe POI::Worksheets do let(:book) { POI::Workbook.open(VARIOUS_SAMPLES_PATH) } it "should allow indexing worksheets by ordinal" do book.worksheets[0].name.should == "text & pic" book.worksheets[1].name.should == "numbers" book.worksheets[2].name.should == "dates" book.worksheets[3].name.should == "bools & errors" end it "should allow indexing worksheets by name" do book.worksheets["text & pic"].name.should == "text & pic" book.worksheets["numbers"].name.should == "numbers" book.worksheets["dates"].name.should == "dates" end it "should be enumerable" do book.worksheets.should be_kind_of Enumerable book.worksheets.each do |sheet| sheet.should be_kind_of POI::Worksheet end book.worksheets.count.should == 5 book.worksheets.collect.count.should == 5 end it "returns cells when passing a cell reference" do - book['dates']['A2'].to_s.should == '2010-02-28' - book['dates']['a2'].to_s.should == '2010-02-28' - book['dates']['B2'].to_s.should == '2010-03-14' - book['dates']['b2'].to_s.should == '2010-03-14' - book['dates']['C2'].to_s.should == '2010-03-28' - book['dates']['c2'].to_s.should == '2010-03-28' + book['dates']['A2'].class.should == DateTime + book['dates']['A2'].to_date.should == Date.parse('2010-02-28') + book['dates']['a2'].to_date.should == Date.parse('2010-02-28') + book['dates']['B2'].to_date.should == Date.parse('2010-03-14') + book['dates']['b2'].to_date.should == Date.parse('2010-03-14') + book['dates']['C2'].to_date.should == Date.parse('2010-03-28') + book['dates']['c2'].to_date.should == Date.parse('2010-03-28') end end describe POI::Rows do it "should be enumerable" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) sheet = book.worksheets["text & pic"] sheet.rows.should be_kind_of Enumerable sheet.rows.each do |row| row.should be_kind_of POI::Row end sheet.rows.count.should == 7 sheet.rows.collect.count.should == 7 end end describe POI::Cells do let(:book) { POI::Workbook.open(VARIOUS_SAMPLES_PATH) } it "should be enumerable" do sheet = book.worksheets["text & pic"] rows = sheet.rows cells = rows[0].cells cells.should be_kind_of Enumerable cells.count.should == 1 cells.collect.count.should == 1 end end describe POI::Cell do let(:book) { POI::Workbook.open(VARIOUS_SAMPLES_PATH) } context "1900 windowed dates" do it "should provide dates for date cells" do sheet = book.worksheets["dates"] rows = sheet.rows dates_by_column = [ - (Date.parse('2010-02-28')..Date.parse('2010-03-14')), - (Date.parse('2010-03-14')..Date.parse('2010-03-28')), - (Date.parse('2010-03-28')..Date.parse('2010-04-11'))] + (DateTime.parse('2010-02-28')..DateTime.parse('2010-03-14')), + (DateTime.parse('2010-03-14')..DateTime.parse('2010-03-28')), + (DateTime.parse('2010-03-28')..DateTime.parse('2010-04-11')) + ] (0..2).each do |col| dates_by_column[col].each_with_index do |date, index| row = index + 1 - rows[row][col].value.should equal_at_cell(date, row, col) + c = sheet.rows[row].cells[col] + c.value.to_date.should == date.to_date end end end end context "1904 windowed dates" do let(:book) { POI::Workbook.open(DATES_1904_WINDOW_XLS_PATH) } it "returns entered dates correctly" do c = book.worksheets[0].rows[1].cells[0] - c.value.to_s.should == "2012-01-01" + c.value.to_date.should == Date.parse("2012-01-01") end it "returns dates computed by a formula correctly" do c = book.worksheets[0].rows[1].cells[3] - c.value.to_s.should == "2012-01-02" + c.value.to_date.should == Date.parse("2012-01-02") end end it "should provide numbers for numeric cells" do sheet = book.worksheets["numbers"] rows = sheet.rows (1..15).each do |number| row = number rows[row][0].value.should equal_at_cell(number, row, 0) rows[row][1].value.should equal_at_cell(number ** 2, row, 1) rows[row][2].value.should equal_at_cell(number ** 3, row, 2) rows[row][3].value.should equal_at_cell(Math.sqrt(number), row, 3) end rows[9][0].to_s.should == '9.0' rows[9][1].to_s.should == '81.0' rows[9][2].to_s.should == '729.0' rows[9][3].to_s.should == '3.0' end it "should handle array access from the workbook down to cells" do book[1][9][0].to_s.should == '9.0' book[1][9][1].to_s.should == '81.0' book[1][9][2].to_s.should == '729.0' book[1][9][3].to_s.should == '3.0' book["numbers"][9][0].to_s.should == '9.0' book["numbers"][9][1].to_s.should == '81.0' book["numbers"][9][2].to_s.should == '729.0' book["numbers"][9][3].to_s.should == '3.0' end it "should provide error text for error cells" do sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[6][0].value.should == 0.0 #'~CIRCULAR~REF~' rows[6][0].error_value.should be_nil rows[7][0].value.should be_nil rows[7][0].error_value.should == '#DIV/0!' rows[8][0].value.should be_nil rows[8][0].error_value.should == '#N/A' rows[9][0].value.should be_nil rows[9][0].error_value.should == '#NAME?' rows[10][0].value.should be_nil rows[10][0].error_value.should == '#NULL!' rows[11][0].value.should be_nil rows[11][0].error_value.should == '#NUM!' rows[12][0].value.should be_nil rows[12][0].error_value.should == '#REF!' rows[13][0].value.should be_nil rows[13][0].error_value.should == '#VALUE!' lambda{ rows[14][0].value }.should_not raise_error(Java::java.lang.RuntimeException) rows[6][0].to_s.should == '0.0' #'~CIRCULAR~REF~' rows[7][0].to_s.should == '' #'#DIV/0!' rows[8][0].to_s.should == '' #'#N/A' rows[9][0].to_s.should == '' #'#NAME?' rows[10][0].to_s.should == '' #'#NULL!' rows[11][0].to_s.should == '' #'#NUM!' rows[12][0].to_s.should == '' #'#REF!' rows[13][0].to_s.should == '' #'#VALUE!' rows[14][0].to_s.should == '' end it "should provide booleans for boolean cells" do sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[1][0].value.should == false rows[1][0].to_s.should == 'false' rows[1][1].value.should == false rows[1][1].to_s.should == 'false' rows[2][0].value.should == true rows[2][0].to_s.should == 'true' rows[2][1].value.should == true rows[2][1].to_s.should == 'true' end it "should provide the cell value as a string" do sheet = book.worksheets["text & pic"] rows = sheet.rows rows[0][0].value.should == "This" rows[1][0].value.should == "is" rows[2][0].value.should == "an" rows[3][0].value.should == "Excel" rows[4][0].value.should == "XLSX" rows[5][0].value.should == "workbook" rows[9][0].value.should == 'This is an Excel XLSX workbook.' rows[0][0].to_s.should == "This" rows[1][0].to_s.should == "is" rows[2][0].to_s.should == "an" rows[3][0].to_s.should == "Excel" rows[4][0].to_s.should == "XLSX" rows[5][0].to_s.should == "workbook" rows[9][0].to_s.should == 'This is an Excel XLSX workbook.' end it "should provide formulas instead of string-ified values" do sheet = book.worksheets["numbers"] rows = sheet.rows (1..15).each do |number| row = number rows[row][0].to_s(false).should == "#{number}.0" rows[row][1].to_s(false).should == "A#{row + 1}*A#{row + 1}" rows[row][2].to_s(false).should == "B#{row + 1}*A#{row + 1}" rows[row][3].to_s(false).should == "SQRT(A#{row + 1})" end sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[1][0].to_s(false).should == '1=2' rows[1][1].to_s(false).should == 'FALSE' rows[2][0].to_s(false).should == '1=1' rows[2][1].to_s(false).should == 'TRUE' rows[14][0].to_s(false).should == 'foobar(1)' sheet = book.worksheets["text & pic"] sheet.rows[9][0].to_s(false).should == 'CONCATENATE(A1," ", A2," ", A3," ", A4," ", A5," ", A6,".")' end it "should handle getting values out of 'non-existent' cells" do sheet = book.worksheets["bools & errors"] sheet.rows[14][2].value.should be_nil end it "should notify the workbook that I have been updated" do - book['dates!A10'].to_s.should == '2010-03-08' - book['dates!A16'].to_s.should == '2010-03-14' - book['dates!B2'].to_s.should == '2010-03-14' + book['dates!A10'].to_date.should == Date.parse('2010-03-08') + book['dates!A16'].to_date.should == Date.parse('2010-03-14') + book['dates!B2'].to_date.should == Date.parse('2010-03-14') cell = book.cell('dates!B2') cell.formula.should == 'A16' cell.formula = 'A10 + 1' book.cell('dates!B2').poi_cell.should === cell.poi_cell book.cell('dates!B2').formula.should == 'A10 + 1' - book['dates!B2'].to_s.should == '2010-03-09' + book['dates!B2'].to_date.should == Date.parse('2010-03-09') end end
kameeoze/jruby-poi
303f1244673919f30c617b2181cabb2c8072ac32
Bugfix: Properly handle 1904 windowed dates.
diff --git a/lib/poi.rb b/lib/poi.rb index e25e149..b42d20f 100644 --- a/lib/poi.rb +++ b/lib/poi.rb @@ -1,14 +1,15 @@ JRUBY_POI_LIB_PATH=File.expand_path(File.dirname(__FILE__)) # Java require 'java' require File.join(JRUBY_POI_LIB_PATH, 'poi-3.8-20120326.jar') require File.join(JRUBY_POI_LIB_PATH, 'poi-ooxml-3.8-20120326.jar') require File.join(JRUBY_POI_LIB_PATH, 'poi-ooxml-schemas-3.8-20120326.jar') require File.join(JRUBY_POI_LIB_PATH, 'poi-scratchpad-3.8-20120326.jar') require File.join(JRUBY_POI_LIB_PATH, 'ooxml-lib', 'xmlbeans-2.3.0.jar') require File.join(JRUBY_POI_LIB_PATH, 'ooxml-lib', 'dom4j-1.6.1.jar') require File.join(JRUBY_POI_LIB_PATH, 'ooxml-lib', 'stax-api-1.0.1.jar') # Ruby require File.join(JRUBY_POI_LIB_PATH, 'poi', 'workbook') +require 'date' # required for Date.parse diff --git a/lib/poi/workbook/cell.rb b/lib/poi/workbook/cell.rb index d7e3449..75acb10 100644 --- a/lib/poi/workbook/cell.rb +++ b/lib/poi/workbook/cell.rb @@ -1,175 +1,159 @@ +# -*- coding: utf-8 -*- module POI class Cells include Enumerable def initialize(row) @row = row @poi_row = row.poi_row @cells = {} end def [](index) @cells[index] ||= Cell.new(@poi_row.cell(index) || @poi_row.create_cell(index), @row) end def size @poi_row.physical_number_of_cells end def each it = @poi_row.cell_iterator yield Cell.new(it.next, @row) while it.has_next end end class Cell < Facade(:poi_cell, org.apache.poi.ss.usermodel.Cell) DATE_UTIL = Java::org.apache.poi.ss.usermodel.DateUtil CELL = Java::org.apache.poi.ss.usermodel.Cell CELL_VALUE = Java::org.apache.poi.ss.usermodel.CellValue CELL_TYPE_BLANK = CELL::CELL_TYPE_BLANK CELL_TYPE_BOOLEAN = CELL::CELL_TYPE_BOOLEAN CELL_TYPE_ERROR = CELL::CELL_TYPE_ERROR CELL_TYPE_FORMULA = CELL::CELL_TYPE_FORMULA CELL_TYPE_NUMERIC = CELL::CELL_TYPE_NUMERIC CELL_TYPE_STRING = CELL::CELL_TYPE_STRING def initialize(cell, row) @cell = cell @row = row end def <=> other return 1 if other.nil? return self.index <=> other.index end # This is NOT an inexpensive operation. The purpose of this method is merely to get more information # out of cell when one thinks the value returned is incorrect. It may have more value in development # than in production. def error_value if poi_cell.cell_type == CELL_TYPE_ERROR error_value_from(poi_cell.error_cell_value) elsif poi_cell.cell_type == CELL_TYPE_FORMULA && poi_cell.cached_formula_result_type == CELL_TYPE_ERROR - # breaks Law of Demeter by reaching into the Row's Worksheet, but it makes sense to do in this case - value_of(@row.worksheet.workbook.formula_evaluator.evaluate(poi_cell)) + cell_value = formula_evaluator.evaluate(poi_cell) + cell_value && error_value_from(cell_value.error_value) else nil end end # returns the formula for this Cell if it has one, otherwise nil def formula_value poi_cell.cell_type == CELL_TYPE_FORMULA ? poi_cell.cell_formula : nil end def value return nil if poi_cell.nil? - value_of(cell_value_for_type(poi_cell.cell_type)) + cast_value end def formula= new_value poi_cell.cell_formula = new_value @row.worksheet.workbook.on_formula_update self self end def formula poi_cell.cell_formula end def value= new_value set_cell_value new_value if new_value.nil? @row.worksheet.workbook.on_delete self else @row.worksheet.workbook.on_update self end self end def comment poi_cell.cell_comment end def index poi_cell.column_index end # Get the String representation of this Cell's value. # # If this Cell is a formula you can pass a false to this method and # get the formula instead of the String representation. def to_s(evaluate_formulas=true) return '' if poi_cell.nil? if poi_cell.cell_type == CELL_TYPE_FORMULA && evaluate_formulas == false formula_value else value.to_s end end # returns the underlying org.apache.poi.ss.usermodel.Cell def poi_cell @cell end # :cell_style= comes from the Façade superclass alias :style= :cell_style= def style! options self.style = @row.worksheet.workbook.create_style(options) end private - def value_of(cell_value) - return nil if cell_value.nil? - - case cell_value.cell_type + def cast_value(type = cell_type) + case type when CELL_TYPE_BLANK then nil - when CELL_TYPE_BOOLEAN then cell_value.boolean_value - when CELL_TYPE_ERROR then error_value_from(cell_value.error_value) - when CELL_TYPE_NUMERIC then numeric_value_from(cell_value) - when CELL_TYPE_STRING then cell_value.string_value - else - raise "unhandled cell type[#{cell_value.cell_type}]" - end - end - - def cell_value_for_type(cell_type) - return nil if cell_type.nil? - begin - case cell_type - when CELL_TYPE_BLANK then nil - when CELL_TYPE_BOOLEAN then CELL_VALUE.value_of(poi_cell.boolean_cell_value) - when CELL_TYPE_FORMULA then cell_value_for_type(poi_cell.cached_formula_result_type) - when CELL_TYPE_STRING then CELL_VALUE.new(poi_cell.string_cell_value) - when CELL_TYPE_ERROR, CELL_TYPE_NUMERIC then CELL_VALUE.new(poi_cell.numeric_cell_value) + when CELL_TYPE_BOOLEAN then get_boolean_cell_value + when CELL_TYPE_ERROR then nil + when CELL_TYPE_FORMULA then cast_value(poi_cell.cached_formula_result_type) + when CELL_TYPE_STRING then get_string_cell_value + when CELL_TYPE_NUMERIC + if DATE_UTIL.cell_date_formatted(poi_cell) + Date.parse(get_date_cell_value.to_s) else - raise "unhandled cell type[#{poi_cell.cell_type}]" + get_numeric_cell_value end - rescue - nil + else + raise "unhandled cell type[#{type}]" end end - - def error_value_from(cell_value) - org.apache.poi.ss.usermodel.ErrorConstants.text(cell_value) + + def workbook + @row.worksheet.workbook end - - def formula_evaluator_for(workbook) - workbook.creation_helper.create_formula_evaluator + + def formula_evaluator + workbook.formula_evaluator end - - def numeric_value_from(cell_value) - if DATE_UTIL.cell_date_formatted(poi_cell) - Date.parse(DATE_UTIL.get_java_date(cell_value.number_value).to_s) - else - cell_value.number_value - end + + def error_value_from(cell_value) + org.apache.poi.ss.usermodel.ErrorConstants.text(cell_value) end end end diff --git a/spec/data/1904_window_dates.xls b/spec/data/1904_window_dates.xls new file mode 100644 index 0000000..bca59a4 Binary files /dev/null and b/spec/data/1904_window_dates.xls differ diff --git a/spec/workbook_spec.rb b/spec/workbook_spec.rb index f0e9da8..7a267d5 100644 --- a/spec/workbook_spec.rb +++ b/spec/workbook_spec.rb @@ -1,351 +1,366 @@ require 'spec_helper' require 'date' require 'stringio' VARIOUS_SAMPLES_PATH = TestDataFile.expand_path("various_samples.xlsx") +DATES_1904_WINDOW_XLS_PATH = TestDataFile.expand_path("1904_window_dates.xls") describe POI::Workbook do it "should open a workbook and allow access to its worksheets" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book.worksheets.size.should == 5 book.filename.should == VARIOUS_SAMPLES_PATH end it "should be able to create a Workbook from an IO object" do content = StringIO.new(open(VARIOUS_SAMPLES_PATH, 'rb'){|f| f.read}) book = POI::Workbook.open(content) book.worksheets.size.should == 5 book.filename.should =~ /spreadsheet.xlsx$/ end it "should be able to create a Workbook from a Java input stream" do content = java.io.FileInputStream.new(VARIOUS_SAMPLES_PATH) book = POI::Workbook.open(content) book.worksheets.size.should == 5 book.filename.should =~ /spreadsheet.xlsx$/ end it "should create an HSSFWorkbook when passed a :format => :hssf option" do book = POI::Workbook.create('test.xls', :format => :hssf) book.poi_workbook.should be_kind_of(org.apache.poi.hssf.usermodel.HSSFWorkbook) end it "should create an XSSFWorkbook when passed a :format => :xssf option" do book = POI::Workbook.create('test.xlsx', :format => :xssf) book.poi_workbook.should be_kind_of(org.apache.poi.xssf.usermodel.XSSFWorkbook) end it "should create an XSSFWorkbook by default" do book = POI::Workbook.create('test.xlsx') book.poi_workbook.should be_kind_of(org.apache.poi.xssf.usermodel.XSSFWorkbook) end it "should return a column of cells by reference" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book["numbers!$A"].should == book['numbers'].rows.collect{|e| e[0].value} book["numbers!A"].should == book['numbers'].rows.collect{|e| e[0].value} book["numbers!C"].should == book['numbers'].rows.collect{|e| e[2].value} book["numbers!$D:$D"].should == book['numbers'].rows.collect{|e| e[3].value} book["numbers!$c:$D"].should == {"C" => book['numbers'].rows.collect{|e| e[2].value}, "D" => book['numbers'].rows.collect{|e| e[3].value}} end it "should return cells by reference" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book.cell("numbers!A1").value.should == 'NUM' book.cell("numbers!A2").to_s.should == '1.0' book.cell("numbers!A3").to_s.should == '2.0' book.cell("numbers!A4").to_s.should == '3.0' book.cell("numbers!A10").to_s.should == '9.0' book.cell("numbers!B10").to_s.should == '81.0' book.cell("numbers!C10").to_s.should == '729.0' book.cell("numbers!D10").to_s.should == '3.0' book.cell("text & pic!A10").value.should == 'This is an Excel XLSX workbook.' book.cell("bools & errors!B3").value.should == true book.cell("high refs!AM619").value.should == 'This is some text' book.cell("high refs!AO624").value.should == 24.0 book.cell("high refs!AP631").value.should == 13.0 book.cell(%Q{'text & pic'!A10}).value.should == 'This is an Excel XLSX workbook.' book.cell(%Q{'bools & errors'!B3}).value.should == true book.cell(%Q{'high refs'!AM619}).value.should == 'This is some text' book.cell(%Q{'high refs'!AO624}).value.should == 24.0 book.cell(%Q{'high refs'!AP631}).value.should == 13.0 end it "should handle named cell ranges" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book.named_ranges.length.should == 3 book.named_ranges.collect{|e| e.name}.should == %w{four_times_six NAMES nums} book.named_ranges.collect{|e| e.sheet.name}.should == ['high refs', 'bools & errors', 'high refs'] book.named_ranges.collect{|e| e.formula}.should == ["'high refs'!$AO$624", "'bools & errors'!$D$2:$D$11", "'high refs'!$AP$619:$AP$631"] book['four_times_six'].should == 24.0 book['nums'].should == (1..13).collect{|e| e * 1.0} # NAMES is a range of empty cells book['NAMES'].should == [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil] book.cell('NAMES').each do | cell | cell.value.should be_nil cell.poi_cell.should_not be_nil cell.to_s.should be_empty end end it "should return an array of cell values by reference" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book['dates!A2:A16'].should == (Date.parse('2010-02-28')..Date.parse('2010-03-14')).to_a end it "should return cell values by reference" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book['text & pic!A10'].should == 'This is an Excel XLSX workbook.' book['bools & errors!B3'].should == true book['high refs!AM619'].should == 'This is some text' book['high refs!AO624'].should == 24.0 book['high refs!AP631'].should == 13.0 end end describe POI::Worksheets do let(:book) { POI::Workbook.open(VARIOUS_SAMPLES_PATH) } it "should allow indexing worksheets by ordinal" do book.worksheets[0].name.should == "text & pic" book.worksheets[1].name.should == "numbers" book.worksheets[2].name.should == "dates" book.worksheets[3].name.should == "bools & errors" end it "should allow indexing worksheets by name" do book.worksheets["text & pic"].name.should == "text & pic" book.worksheets["numbers"].name.should == "numbers" book.worksheets["dates"].name.should == "dates" end it "should be enumerable" do book.worksheets.should be_kind_of Enumerable book.worksheets.each do |sheet| sheet.should be_kind_of POI::Worksheet end book.worksheets.count.should == 5 book.worksheets.collect.count.should == 5 end it "returns cells when passing a cell reference" do book['dates']['A2'].to_s.should == '2010-02-28' book['dates']['a2'].to_s.should == '2010-02-28' book['dates']['B2'].to_s.should == '2010-03-14' book['dates']['b2'].to_s.should == '2010-03-14' book['dates']['C2'].to_s.should == '2010-03-28' book['dates']['c2'].to_s.should == '2010-03-28' end end describe POI::Rows do it "should be enumerable" do book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) sheet = book.worksheets["text & pic"] sheet.rows.should be_kind_of Enumerable sheet.rows.each do |row| row.should be_kind_of POI::Row end sheet.rows.count.should == 7 sheet.rows.collect.count.should == 7 end end describe POI::Cells do let(:book) { POI::Workbook.open(VARIOUS_SAMPLES_PATH) } it "should be enumerable" do sheet = book.worksheets["text & pic"] rows = sheet.rows cells = rows[0].cells cells.should be_kind_of Enumerable cells.count.should == 1 cells.collect.count.should == 1 end end describe POI::Cell do - let(:book) { POI::Workbook.open(VARIOUS_SAMPLES_PATH) } + let(:book) { POI::Workbook.open(VARIOUS_SAMPLES_PATH) } - it "should provide dates for date cells" do - sheet = book.worksheets["dates"] - rows = sheet.rows - - dates_by_column = [ - (Date.parse('2010-02-28')..Date.parse('2010-03-14')), - (Date.parse('2010-03-14')..Date.parse('2010-03-28')), - (Date.parse('2010-03-28')..Date.parse('2010-04-11'))] - (0..2).each do |col| - dates_by_column[col].each_with_index do |date, index| - row = index + 1 - rows[row][col].value.should equal_at_cell(date, row, col) + context "1900 windowed dates" do + it "should provide dates for date cells" do + sheet = book.worksheets["dates"] + rows = sheet.rows + + dates_by_column = [ + (Date.parse('2010-02-28')..Date.parse('2010-03-14')), + (Date.parse('2010-03-14')..Date.parse('2010-03-28')), + (Date.parse('2010-03-28')..Date.parse('2010-04-11'))] + (0..2).each do |col| + dates_by_column[col].each_with_index do |date, index| + row = index + 1 + rows[row][col].value.should equal_at_cell(date, row, col) + end end - + end + end + + context "1904 windowed dates" do + let(:book) { POI::Workbook.open(DATES_1904_WINDOW_XLS_PATH) } + it "returns entered dates correctly" do + c = book.worksheets[0].rows[1].cells[0] + c.value.to_s.should == "2012-01-01" + end + + it "returns dates computed by a formula correctly" do + c = book.worksheets[0].rows[1].cells[3] + c.value.to_s.should == "2012-01-02" end end it "should provide numbers for numeric cells" do sheet = book.worksheets["numbers"] rows = sheet.rows (1..15).each do |number| row = number rows[row][0].value.should equal_at_cell(number, row, 0) rows[row][1].value.should equal_at_cell(number ** 2, row, 1) rows[row][2].value.should equal_at_cell(number ** 3, row, 2) rows[row][3].value.should equal_at_cell(Math.sqrt(number), row, 3) end rows[9][0].to_s.should == '9.0' rows[9][1].to_s.should == '81.0' rows[9][2].to_s.should == '729.0' rows[9][3].to_s.should == '3.0' end it "should handle array access from the workbook down to cells" do book[1][9][0].to_s.should == '9.0' book[1][9][1].to_s.should == '81.0' book[1][9][2].to_s.should == '729.0' book[1][9][3].to_s.should == '3.0' book["numbers"][9][0].to_s.should == '9.0' book["numbers"][9][1].to_s.should == '81.0' book["numbers"][9][2].to_s.should == '729.0' book["numbers"][9][3].to_s.should == '3.0' end it "should provide error text for error cells" do sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[6][0].value.should == 0.0 #'~CIRCULAR~REF~' rows[6][0].error_value.should be_nil rows[7][0].value.should be_nil rows[7][0].error_value.should == '#DIV/0!' rows[8][0].value.should be_nil rows[8][0].error_value.should == '#N/A' rows[9][0].value.should be_nil rows[9][0].error_value.should == '#NAME?' rows[10][0].value.should be_nil rows[10][0].error_value.should == '#NULL!' rows[11][0].value.should be_nil rows[11][0].error_value.should == '#NUM!' rows[12][0].value.should be_nil rows[12][0].error_value.should == '#REF!' rows[13][0].value.should be_nil rows[13][0].error_value.should == '#VALUE!' lambda{ rows[14][0].value }.should_not raise_error(Java::java.lang.RuntimeException) rows[6][0].to_s.should == '0.0' #'~CIRCULAR~REF~' rows[7][0].to_s.should == '' #'#DIV/0!' rows[8][0].to_s.should == '' #'#N/A' rows[9][0].to_s.should == '' #'#NAME?' rows[10][0].to_s.should == '' #'#NULL!' rows[11][0].to_s.should == '' #'#NUM!' rows[12][0].to_s.should == '' #'#REF!' rows[13][0].to_s.should == '' #'#VALUE!' rows[14][0].to_s.should == '' end it "should provide booleans for boolean cells" do sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[1][0].value.should == false rows[1][0].to_s.should == 'false' rows[1][1].value.should == false rows[1][1].to_s.should == 'false' rows[2][0].value.should == true rows[2][0].to_s.should == 'true' rows[2][1].value.should == true rows[2][1].to_s.should == 'true' end it "should provide the cell value as a string" do sheet = book.worksheets["text & pic"] rows = sheet.rows rows[0][0].value.should == "This" rows[1][0].value.should == "is" rows[2][0].value.should == "an" rows[3][0].value.should == "Excel" rows[4][0].value.should == "XLSX" rows[5][0].value.should == "workbook" rows[9][0].value.should == 'This is an Excel XLSX workbook.' rows[0][0].to_s.should == "This" rows[1][0].to_s.should == "is" rows[2][0].to_s.should == "an" rows[3][0].to_s.should == "Excel" rows[4][0].to_s.should == "XLSX" rows[5][0].to_s.should == "workbook" rows[9][0].to_s.should == 'This is an Excel XLSX workbook.' end it "should provide formulas instead of string-ified values" do sheet = book.worksheets["numbers"] rows = sheet.rows (1..15).each do |number| row = number rows[row][0].to_s(false).should == "#{number}.0" rows[row][1].to_s(false).should == "A#{row + 1}*A#{row + 1}" rows[row][2].to_s(false).should == "B#{row + 1}*A#{row + 1}" rows[row][3].to_s(false).should == "SQRT(A#{row + 1})" end sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[1][0].to_s(false).should == '1=2' rows[1][1].to_s(false).should == 'FALSE' rows[2][0].to_s(false).should == '1=1' rows[2][1].to_s(false).should == 'TRUE' rows[14][0].to_s(false).should == 'foobar(1)' sheet = book.worksheets["text & pic"] sheet.rows[9][0].to_s(false).should == 'CONCATENATE(A1," ", A2," ", A3," ", A4," ", A5," ", A6,".")' end it "should handle getting values out of 'non-existent' cells" do sheet = book.worksheets["bools & errors"] sheet.rows[14][2].value.should be_nil end it "should notify the workbook that I have been updated" do book['dates!A10'].to_s.should == '2010-03-08' book['dates!A16'].to_s.should == '2010-03-14' book['dates!B2'].to_s.should == '2010-03-14' cell = book.cell('dates!B2') cell.formula.should == 'A16' cell.formula = 'A10 + 1' book.cell('dates!B2').poi_cell.should === cell.poi_cell book.cell('dates!B2').formula.should == 'A10 + 1' book['dates!B2'].to_s.should == '2010-03-09' end end
kameeoze/jruby-poi
112c5650dc27d173f94e0f8801a0011c6de7a164
use let statement, constants in workbook_spec
diff --git a/spec/workbook_spec.rb b/spec/workbook_spec.rb index f1675ab..f0e9da8 100644 --- a/spec/workbook_spec.rb +++ b/spec/workbook_spec.rb @@ -1,385 +1,351 @@ require 'spec_helper' require 'date' require 'stringio' +VARIOUS_SAMPLES_PATH = TestDataFile.expand_path("various_samples.xlsx") + describe POI::Workbook do it "should open a workbook and allow access to its worksheets" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) + book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book.worksheets.size.should == 5 - book.filename.should == name + book.filename.should == VARIOUS_SAMPLES_PATH end it "should be able to create a Workbook from an IO object" do - content = StringIO.new(open(TestDataFile.expand_path("various_samples.xlsx"), 'rb'){|f| f.read}) + content = StringIO.new(open(VARIOUS_SAMPLES_PATH, 'rb'){|f| f.read}) book = POI::Workbook.open(content) book.worksheets.size.should == 5 book.filename.should =~ /spreadsheet.xlsx$/ end it "should be able to create a Workbook from a Java input stream" do - content = java.io.FileInputStream.new(TestDataFile.expand_path("various_samples.xlsx")) + content = java.io.FileInputStream.new(VARIOUS_SAMPLES_PATH) book = POI::Workbook.open(content) book.worksheets.size.should == 5 book.filename.should =~ /spreadsheet.xlsx$/ end it "should create an HSSFWorkbook when passed a :format => :hssf option" do book = POI::Workbook.create('test.xls', :format => :hssf) book.poi_workbook.should be_kind_of(org.apache.poi.hssf.usermodel.HSSFWorkbook) end it "should create an XSSFWorkbook when passed a :format => :xssf option" do book = POI::Workbook.create('test.xlsx', :format => :xssf) book.poi_workbook.should be_kind_of(org.apache.poi.xssf.usermodel.XSSFWorkbook) end it "should create an XSSFWorkbook by default" do book = POI::Workbook.create('test.xlsx') book.poi_workbook.should be_kind_of(org.apache.poi.xssf.usermodel.XSSFWorkbook) end it "should return a column of cells by reference" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) + book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book["numbers!$A"].should == book['numbers'].rows.collect{|e| e[0].value} book["numbers!A"].should == book['numbers'].rows.collect{|e| e[0].value} book["numbers!C"].should == book['numbers'].rows.collect{|e| e[2].value} book["numbers!$D:$D"].should == book['numbers'].rows.collect{|e| e[3].value} book["numbers!$c:$D"].should == {"C" => book['numbers'].rows.collect{|e| e[2].value}, "D" => book['numbers'].rows.collect{|e| e[3].value}} end it "should return cells by reference" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) + book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book.cell("numbers!A1").value.should == 'NUM' book.cell("numbers!A2").to_s.should == '1.0' book.cell("numbers!A3").to_s.should == '2.0' book.cell("numbers!A4").to_s.should == '3.0' book.cell("numbers!A10").to_s.should == '9.0' book.cell("numbers!B10").to_s.should == '81.0' book.cell("numbers!C10").to_s.should == '729.0' book.cell("numbers!D10").to_s.should == '3.0' book.cell("text & pic!A10").value.should == 'This is an Excel XLSX workbook.' book.cell("bools & errors!B3").value.should == true book.cell("high refs!AM619").value.should == 'This is some text' book.cell("high refs!AO624").value.should == 24.0 book.cell("high refs!AP631").value.should == 13.0 book.cell(%Q{'text & pic'!A10}).value.should == 'This is an Excel XLSX workbook.' book.cell(%Q{'bools & errors'!B3}).value.should == true book.cell(%Q{'high refs'!AM619}).value.should == 'This is some text' book.cell(%Q{'high refs'!AO624}).value.should == 24.0 book.cell(%Q{'high refs'!AP631}).value.should == 13.0 end it "should handle named cell ranges" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) + book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book.named_ranges.length.should == 3 book.named_ranges.collect{|e| e.name}.should == %w{four_times_six NAMES nums} book.named_ranges.collect{|e| e.sheet.name}.should == ['high refs', 'bools & errors', 'high refs'] book.named_ranges.collect{|e| e.formula}.should == ["'high refs'!$AO$624", "'bools & errors'!$D$2:$D$11", "'high refs'!$AP$619:$AP$631"] book['four_times_six'].should == 24.0 book['nums'].should == (1..13).collect{|e| e * 1.0} # NAMES is a range of empty cells book['NAMES'].should == [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil] book.cell('NAMES').each do | cell | cell.value.should be_nil cell.poi_cell.should_not be_nil cell.to_s.should be_empty end end it "should return an array of cell values by reference" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) + book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book['dates!A2:A16'].should == (Date.parse('2010-02-28')..Date.parse('2010-03-14')).to_a end it "should return cell values by reference" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) + book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) book['text & pic!A10'].should == 'This is an Excel XLSX workbook.' book['bools & errors!B3'].should == true book['high refs!AM619'].should == 'This is some text' book['high refs!AO624'].should == 24.0 book['high refs!AP631'].should == 13.0 end end describe POI::Worksheets do - it "should allow indexing worksheets by ordinal" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) + let(:book) { POI::Workbook.open(VARIOUS_SAMPLES_PATH) } + it "should allow indexing worksheets by ordinal" do book.worksheets[0].name.should == "text & pic" book.worksheets[1].name.should == "numbers" book.worksheets[2].name.should == "dates" book.worksheets[3].name.should == "bools & errors" end it "should allow indexing worksheets by name" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) - book.worksheets["text & pic"].name.should == "text & pic" book.worksheets["numbers"].name.should == "numbers" book.worksheets["dates"].name.should == "dates" end it "should be enumerable" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) book.worksheets.should be_kind_of Enumerable book.worksheets.each do |sheet| sheet.should be_kind_of POI::Worksheet end book.worksheets.count.should == 5 book.worksheets.collect.count.should == 5 end it "returns cells when passing a cell reference" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) book['dates']['A2'].to_s.should == '2010-02-28' book['dates']['a2'].to_s.should == '2010-02-28' book['dates']['B2'].to_s.should == '2010-03-14' book['dates']['b2'].to_s.should == '2010-03-14' book['dates']['C2'].to_s.should == '2010-03-28' book['dates']['c2'].to_s.should == '2010-03-28' end end describe POI::Rows do it "should be enumerable" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) + book = POI::Workbook.open(VARIOUS_SAMPLES_PATH) sheet = book.worksheets["text & pic"] sheet.rows.should be_kind_of Enumerable sheet.rows.each do |row| row.should be_kind_of POI::Row end sheet.rows.count.should == 7 sheet.rows.collect.count.should == 7 end end describe POI::Cells do - before :each do - @name = TestDataFile.expand_path("various_samples.xlsx") - @book = POI::Workbook.open(@name) - end - - def book - @book - end + let(:book) { POI::Workbook.open(VARIOUS_SAMPLES_PATH) } - def name - @name - end - it "should be enumerable" do sheet = book.worksheets["text & pic"] rows = sheet.rows cells = rows[0].cells cells.should be_kind_of Enumerable cells.count.should == 1 cells.collect.count.should == 1 end end describe POI::Cell do - before :each do - @name = TestDataFile.expand_path("various_samples.xlsx") - @book = POI::Workbook.open(@name) - end - - def book - @book - end - - def name - @name - end + let(:book) { POI::Workbook.open(VARIOUS_SAMPLES_PATH) } it "should provide dates for date cells" do sheet = book.worksheets["dates"] rows = sheet.rows dates_by_column = [ (Date.parse('2010-02-28')..Date.parse('2010-03-14')), (Date.parse('2010-03-14')..Date.parse('2010-03-28')), (Date.parse('2010-03-28')..Date.parse('2010-04-11'))] (0..2).each do |col| dates_by_column[col].each_with_index do |date, index| row = index + 1 rows[row][col].value.should equal_at_cell(date, row, col) end + end end it "should provide numbers for numeric cells" do sheet = book.worksheets["numbers"] rows = sheet.rows (1..15).each do |number| row = number rows[row][0].value.should equal_at_cell(number, row, 0) rows[row][1].value.should equal_at_cell(number ** 2, row, 1) rows[row][2].value.should equal_at_cell(number ** 3, row, 2) rows[row][3].value.should equal_at_cell(Math.sqrt(number), row, 3) end rows[9][0].to_s.should == '9.0' rows[9][1].to_s.should == '81.0' rows[9][2].to_s.should == '729.0' rows[9][3].to_s.should == '3.0' end it "should handle array access from the workbook down to cells" do book[1][9][0].to_s.should == '9.0' book[1][9][1].to_s.should == '81.0' book[1][9][2].to_s.should == '729.0' book[1][9][3].to_s.should == '3.0' book["numbers"][9][0].to_s.should == '9.0' book["numbers"][9][1].to_s.should == '81.0' book["numbers"][9][2].to_s.should == '729.0' book["numbers"][9][3].to_s.should == '3.0' end it "should provide error text for error cells" do sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[6][0].value.should == 0.0 #'~CIRCULAR~REF~' rows[6][0].error_value.should be_nil rows[7][0].value.should be_nil rows[7][0].error_value.should == '#DIV/0!' rows[8][0].value.should be_nil rows[8][0].error_value.should == '#N/A' rows[9][0].value.should be_nil rows[9][0].error_value.should == '#NAME?' rows[10][0].value.should be_nil rows[10][0].error_value.should == '#NULL!' rows[11][0].value.should be_nil rows[11][0].error_value.should == '#NUM!' rows[12][0].value.should be_nil rows[12][0].error_value.should == '#REF!' rows[13][0].value.should be_nil rows[13][0].error_value.should == '#VALUE!' lambda{ rows[14][0].value }.should_not raise_error(Java::java.lang.RuntimeException) rows[6][0].to_s.should == '0.0' #'~CIRCULAR~REF~' rows[7][0].to_s.should == '' #'#DIV/0!' rows[8][0].to_s.should == '' #'#N/A' rows[9][0].to_s.should == '' #'#NAME?' rows[10][0].to_s.should == '' #'#NULL!' rows[11][0].to_s.should == '' #'#NUM!' rows[12][0].to_s.should == '' #'#REF!' rows[13][0].to_s.should == '' #'#VALUE!' rows[14][0].to_s.should == '' end it "should provide booleans for boolean cells" do sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[1][0].value.should == false rows[1][0].to_s.should == 'false' rows[1][1].value.should == false rows[1][1].to_s.should == 'false' rows[2][0].value.should == true rows[2][0].to_s.should == 'true' rows[2][1].value.should == true rows[2][1].to_s.should == 'true' end it "should provide the cell value as a string" do sheet = book.worksheets["text & pic"] rows = sheet.rows rows[0][0].value.should == "This" rows[1][0].value.should == "is" rows[2][0].value.should == "an" rows[3][0].value.should == "Excel" rows[4][0].value.should == "XLSX" rows[5][0].value.should == "workbook" rows[9][0].value.should == 'This is an Excel XLSX workbook.' rows[0][0].to_s.should == "This" rows[1][0].to_s.should == "is" rows[2][0].to_s.should == "an" rows[3][0].to_s.should == "Excel" rows[4][0].to_s.should == "XLSX" rows[5][0].to_s.should == "workbook" rows[9][0].to_s.should == 'This is an Excel XLSX workbook.' end it "should provide formulas instead of string-ified values" do sheet = book.worksheets["numbers"] rows = sheet.rows (1..15).each do |number| row = number rows[row][0].to_s(false).should == "#{number}.0" rows[row][1].to_s(false).should == "A#{row + 1}*A#{row + 1}" rows[row][2].to_s(false).should == "B#{row + 1}*A#{row + 1}" rows[row][3].to_s(false).should == "SQRT(A#{row + 1})" end sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[1][0].to_s(false).should == '1=2' rows[1][1].to_s(false).should == 'FALSE' rows[2][0].to_s(false).should == '1=1' rows[2][1].to_s(false).should == 'TRUE' rows[14][0].to_s(false).should == 'foobar(1)' sheet = book.worksheets["text & pic"] sheet.rows[9][0].to_s(false).should == 'CONCATENATE(A1," ", A2," ", A3," ", A4," ", A5," ", A6,".")' end it "should handle getting values out of 'non-existent' cells" do sheet = book.worksheets["bools & errors"] sheet.rows[14][2].value.should be_nil end it "should notify the workbook that I have been updated" do book['dates!A10'].to_s.should == '2010-03-08' book['dates!A16'].to_s.should == '2010-03-14' book['dates!B2'].to_s.should == '2010-03-14' cell = book.cell('dates!B2') cell.formula.should == 'A16' cell.formula = 'A10 + 1' book.cell('dates!B2').poi_cell.should === cell.poi_cell book.cell('dates!B2').formula.should == 'A10 + 1' book['dates!B2'].to_s.should == '2010-03-09' end end
kameeoze/jruby-poi
fb0bd8d185ad85b340054c056c6e296473e7f933
trying out TDDium
diff --git a/tddium.yml b/tddium.yml new file mode 100644 index 0000000..64ced05 --- /dev/null +++ b/tddium.yml @@ -0,0 +1,11 @@ +:tddium: + :ruby_version: ruby-1.9.2-p312 jruby-1.6.7 + :tests: + - type: custom + invocation: single + output: exit-status + command: JRUBY_OPTS=--1.8 bundle install && bundle exec env JRUBY_OPTS=--1.8 rake spec + - type: custom + invocation: single + output: exit-status + command: bundle exec env JRUBY_OPTS=--1.9 rake spec \ No newline at end of file
kameeoze/jruby-poi
0fa5a4e3e4ceea7a0b3ee6ddfd984da6ddb4abf7
Regenerate gemspec for version 0.9.0
diff --git a/jruby-poi.gemspec b/jruby-poi.gemspec index 190bc95..a0f241e 100644 --- a/jruby-poi.gemspec +++ b/jruby-poi.gemspec @@ -1,82 +1,85 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "jruby-poi" s.version = "0.9.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Scott Deming", "Jason Rogers"] s.date = "2012-10-15" s.description = "A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI." s.email = ["[email protected]", "[email protected]"] s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ ".travis.yml", "Gemfile", "Gemfile.lock", "LICENSE", "NOTICE", "README.markdown", "Rakefile", "VERSION", "jruby-poi.gemspec", "lib/ooxml-lib/dom4j-1.6.1.jar", "lib/ooxml-lib/stax-api-1.0.1.jar", "lib/ooxml-lib/xmlbeans-2.3.0.jar", "lib/poi-3.8-20120326.jar", "lib/poi-examples-3.8-20120326.jar", "lib/poi-excelant-3.8-20120326.jar", "lib/poi-ooxml-3.8-20120326.jar", "lib/poi-ooxml-schemas-3.8-20120326.jar", "lib/poi-scratchpad-3.8-20120326.jar", "lib/poi.rb", "lib/poi/workbook.rb", "lib/poi/workbook/area.rb", "lib/poi/workbook/cell.rb", "lib/poi/workbook/named_range.rb", "lib/poi/workbook/row.rb", "lib/poi/workbook/workbook.rb", "lib/poi/workbook/worksheet.rb", "spec/data/simple_with_picture.ods", "spec/data/simple_with_picture.xls", "spec/data/spreadsheet.ods", "spec/data/timesheet.xlsx", "spec/data/various_samples.xlsx", "spec/facade_spec.rb", "spec/io_spec.rb", "spec/spec_helper.rb", "spec/support/java/jrubypoi/MockOutputStream.java", "spec/support/java/support.jar", "spec/support/matchers/cell_matcher.rb", "spec/workbook_spec.rb", "spec/writing_spec.rb", "spec_debug.sh" ] s.homepage = "http://github.com/kameeoze/jruby-poi" s.licenses = ["Apache"] s.require_paths = ["lib"] s.rubygems_version = "1.8.24" s.summary = "Apache POI class library for jruby" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, [">= 2.11.0"]) s.add_development_dependency(%q<jeweler>, [">= 1.8.4"]) + s.add_development_dependency(%q<jruby-openssl>, [">= 0"]) else s.add_dependency(%q<rspec>, [">= 2.11.0"]) s.add_dependency(%q<jeweler>, [">= 1.8.4"]) + s.add_dependency(%q<jruby-openssl>, [">= 0"]) end else s.add_dependency(%q<rspec>, [">= 2.11.0"]) s.add_dependency(%q<jeweler>, [">= 1.8.4"]) + s.add_dependency(%q<jruby-openssl>, [">= 0"]) end end
kameeoze/jruby-poi
39d4d24e821f6aed78cbc23b069d66f39452f7e8
Add jruby-openssl to Gemfile, needed for releasing a gem.
diff --git a/Gemfile b/Gemfile index 043fdfe..1127d64 100644 --- a/Gemfile +++ b/Gemfile @@ -1,8 +1,9 @@ source "http://rubygems.org" # Add dependencies to develop your gem here. # Include everything needed to run rake, tests, features, etc. group :development do gem "rspec", ">= 2.11.0" gem "jeweler", ">= 1.8.4" + gem "jruby-openssl" end diff --git a/Gemfile.lock b/Gemfile.lock index 7ab4e34..30afafc 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,31 +1,35 @@ GEM remote: http://rubygems.org/ specs: + bouncy-castle-java (1.5.0146.1) diff-lcs (1.1.3) git (1.2.5) jeweler (1.8.4) bundler (~> 1.0) git (>= 1.2.5) rake rdoc + jruby-openssl (0.7.7) + bouncy-castle-java (>= 1.5.0146.1) json (1.7.3) json (1.7.3-java) rake (0.9.2.2) rdoc (3.12) json (~> 1.4) rspec (2.11.0) rspec-core (~> 2.11.0) rspec-expectations (~> 2.11.0) rspec-mocks (~> 2.11.0) rspec-core (2.11.1) rspec-expectations (2.11.1) diff-lcs (~> 1.1.3) rspec-mocks (2.11.1) PLATFORMS java ruby DEPENDENCIES jeweler (>= 1.8.4) + jruby-openssl rspec (>= 2.11.0)
kameeoze/jruby-poi
78efd3881f787762e6345bb669c6bd245f81144a
Release prep
diff --git a/jruby-poi.gemspec b/jruby-poi.gemspec index f038c49..190bc95 100644 --- a/jruby-poi.gemspec +++ b/jruby-poi.gemspec @@ -1,83 +1,82 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| - s.name = %q{jruby-poi} + s.name = "jruby-poi" s.version = "0.9.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.authors = [%q{Scott Deming}, %q{Jason Rogers}] - s.date = %q{2012-07-23} - s.description = %q{A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI.} - s.email = [%q{[email protected]}, %q{[email protected]}] - s.executables = [] + s.authors = ["Scott Deming", "Jason Rogers"] + s.date = "2012-10-15" + s.description = "A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI." + s.email = ["[email protected]", "[email protected]"] s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ ".travis.yml", "Gemfile", "Gemfile.lock", "LICENSE", "NOTICE", "README.markdown", "Rakefile", "VERSION", "jruby-poi.gemspec", "lib/ooxml-lib/dom4j-1.6.1.jar", "lib/ooxml-lib/stax-api-1.0.1.jar", "lib/ooxml-lib/xmlbeans-2.3.0.jar", "lib/poi-3.8-20120326.jar", "lib/poi-examples-3.8-20120326.jar", "lib/poi-excelant-3.8-20120326.jar", "lib/poi-ooxml-3.8-20120326.jar", "lib/poi-ooxml-schemas-3.8-20120326.jar", "lib/poi-scratchpad-3.8-20120326.jar", "lib/poi.rb", "lib/poi/workbook.rb", "lib/poi/workbook/area.rb", "lib/poi/workbook/cell.rb", "lib/poi/workbook/named_range.rb", "lib/poi/workbook/row.rb", "lib/poi/workbook/workbook.rb", "lib/poi/workbook/worksheet.rb", "spec/data/simple_with_picture.ods", "spec/data/simple_with_picture.xls", "spec/data/spreadsheet.ods", "spec/data/timesheet.xlsx", "spec/data/various_samples.xlsx", "spec/facade_spec.rb", "spec/io_spec.rb", "spec/spec_helper.rb", "spec/support/java/jrubypoi/MockOutputStream.java", "spec/support/java/support.jar", "spec/support/matchers/cell_matcher.rb", "spec/workbook_spec.rb", "spec/writing_spec.rb", "spec_debug.sh" ] - s.homepage = %q{http://github.com/kameeoze/jruby-poi} - s.licenses = [%q{Apache}] - s.require_paths = [%q{lib}] - s.rubygems_version = %q{1.8.9} - s.summary = %q{Apache POI class library for jruby} + s.homepage = "http://github.com/kameeoze/jruby-poi" + s.licenses = ["Apache"] + s.require_paths = ["lib"] + s.rubygems_version = "1.8.24" + s.summary = "Apache POI class library for jruby" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, [">= 2.11.0"]) s.add_development_dependency(%q<jeweler>, [">= 1.8.4"]) else s.add_dependency(%q<rspec>, [">= 2.11.0"]) s.add_dependency(%q<jeweler>, [">= 1.8.4"]) end else s.add_dependency(%q<rspec>, [">= 2.11.0"]) s.add_dependency(%q<jeweler>, [">= 1.8.4"]) end end
kameeoze/jruby-poi
e520bf296a872ef6c1f8cdae8412354e2ed189de
Remove other gems' executables
diff --git a/bin/autospec b/bin/autospec deleted file mode 100755 index 3ee978f..0000000 --- a/bin/autospec +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env jruby -# -# This file was generated by Bundler. -# -# The application 'autospec' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -require 'pathname' -ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile", - Pathname.new(__FILE__).realpath) - -require 'rubygems' -require 'bundler/setup' - -load Gem.bin_path('rspec-core', 'autospec') diff --git a/bin/htmldiff b/bin/htmldiff deleted file mode 100755 index 8cd1f8f..0000000 --- a/bin/htmldiff +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env jruby -# -# This file was generated by Bundler. -# -# The application 'htmldiff' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -require 'pathname' -ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile", - Pathname.new(__FILE__).realpath) - -require 'rubygems' -require 'bundler/setup' - -load Gem.bin_path('diff-lcs', 'htmldiff') diff --git a/bin/ldiff b/bin/ldiff deleted file mode 100755 index 9b9eaf0..0000000 --- a/bin/ldiff +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env jruby -# -# This file was generated by Bundler. -# -# The application 'ldiff' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -require 'pathname' -ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile", - Pathname.new(__FILE__).realpath) - -require 'rubygems' -require 'bundler/setup' - -load Gem.bin_path('diff-lcs', 'ldiff') diff --git a/bin/rdebug b/bin/rdebug deleted file mode 100755 index b7fc16f..0000000 --- a/bin/rdebug +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env jruby -# -# This file was generated by Bundler. -# -# The application 'rdebug' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -require 'pathname' -ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile", - Pathname.new(__FILE__).realpath) - -require 'rubygems' -require 'bundler/setup' - -load Gem.bin_path('ruby-debug', 'rdebug') diff --git a/bin/rspec b/bin/rspec deleted file mode 100755 index b80cb91..0000000 --- a/bin/rspec +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env jruby -# -# This file was generated by Bundler. -# -# The application 'rspec' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -require 'pathname' -ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile", - Pathname.new(__FILE__).realpath) - -require 'rubygems' -require 'bundler/setup' - -load Gem.bin_path('rspec-core', 'rspec') diff --git a/jruby-poi.gemspec b/jruby-poi.gemspec index 23b3a2f..f038c49 100644 --- a/jruby-poi.gemspec +++ b/jruby-poi.gemspec @@ -1,88 +1,83 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{jruby-poi} s.version = "0.9.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = [%q{Scott Deming}, %q{Jason Rogers}] s.date = %q{2012-07-23} s.description = %q{A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI.} s.email = [%q{[email protected]}, %q{[email protected]}] - s.executables = [%q{autospec}, %q{htmldiff}, %q{ldiff}, %q{rdebug}, %q{rspec}] + s.executables = [] s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ ".travis.yml", "Gemfile", "Gemfile.lock", "LICENSE", "NOTICE", "README.markdown", "Rakefile", "VERSION", - "bin/autospec", - "bin/htmldiff", - "bin/ldiff", - "bin/rdebug", - "bin/rspec", "jruby-poi.gemspec", "lib/ooxml-lib/dom4j-1.6.1.jar", "lib/ooxml-lib/stax-api-1.0.1.jar", "lib/ooxml-lib/xmlbeans-2.3.0.jar", "lib/poi-3.8-20120326.jar", "lib/poi-examples-3.8-20120326.jar", "lib/poi-excelant-3.8-20120326.jar", "lib/poi-ooxml-3.8-20120326.jar", "lib/poi-ooxml-schemas-3.8-20120326.jar", "lib/poi-scratchpad-3.8-20120326.jar", "lib/poi.rb", "lib/poi/workbook.rb", "lib/poi/workbook/area.rb", "lib/poi/workbook/cell.rb", "lib/poi/workbook/named_range.rb", "lib/poi/workbook/row.rb", "lib/poi/workbook/workbook.rb", "lib/poi/workbook/worksheet.rb", "spec/data/simple_with_picture.ods", "spec/data/simple_with_picture.xls", "spec/data/spreadsheet.ods", "spec/data/timesheet.xlsx", "spec/data/various_samples.xlsx", "spec/facade_spec.rb", "spec/io_spec.rb", "spec/spec_helper.rb", "spec/support/java/jrubypoi/MockOutputStream.java", "spec/support/java/support.jar", "spec/support/matchers/cell_matcher.rb", "spec/workbook_spec.rb", "spec/writing_spec.rb", "spec_debug.sh" ] s.homepage = %q{http://github.com/kameeoze/jruby-poi} s.licenses = [%q{Apache}] s.require_paths = [%q{lib}] s.rubygems_version = %q{1.8.9} s.summary = %q{Apache POI class library for jruby} if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, [">= 2.11.0"]) s.add_development_dependency(%q<jeweler>, [">= 1.8.4"]) else s.add_dependency(%q<rspec>, [">= 2.11.0"]) s.add_dependency(%q<jeweler>, [">= 1.8.4"]) end else s.add_dependency(%q<rspec>, [">= 2.11.0"]) s.add_dependency(%q<jeweler>, [">= 1.8.4"]) end end
kameeoze/jruby-poi
96935d524cdd999ae8f81ff3277f5b48a80fc420
Add support for creating HSSFWorkbooks
diff --git a/lib/poi/workbook/workbook.rb b/lib/poi/workbook/workbook.rb index 266b7f1..ad22f5a 100644 --- a/lib/poi/workbook/workbook.rb +++ b/lib/poi/workbook/workbook.rb @@ -1,262 +1,268 @@ require 'tmpdir' require 'stringio' require 'java' module POI class Workbook < Facade(:poi_workbook, org.apache.poi.ss.usermodel.Workbook) FONT = org.apache.poi.ss.usermodel.Font FONT_CONSTANTS = Hash[*FONT.constants.map{|e| [e.downcase.to_sym, FONT.const_get(e)]}.flatten] CELL_STYLE = org.apache.poi.ss.usermodel.CellStyle CELL_STYLE_CONSTANTS = Hash[*CELL_STYLE.constants.map{|e| [e.downcase.to_sym, CELL_STYLE.const_get(e)]}.flatten] INDEXED_COLORS = org.apache.poi.ss.usermodel.IndexedColors INDEXED_COLORS_CONSTANTS = Hash[*INDEXED_COLORS.constants.map{|e| [e.downcase.to_sym, INDEXED_COLORS.const_get(e)]}.flatten] def self.open(filename_or_stream) name, stream = if filename_or_stream.kind_of?(java.io.InputStream) [File.join(Dir.tmpdir, "spreadsheet.xlsx"), filename_or_stream] elsif filename_or_stream.kind_of?(IO) || StringIO === filename_or_stream || filename_or_stream.respond_to?(:read) # NOTE: the String.unpack here can be very inefficient on large files [File.join(Dir.tmpdir, "spreadsheet.xlsx"), java.io.ByteArrayInputStream.new(filename_or_stream.read.unpack('c*').to_java(:byte))] else raise Exception, "FileNotFound" unless File.exists?( filename_or_stream ) [filename_or_stream, java.io.FileInputStream.new(filename_or_stream)] end instance = self.new(name, stream) if block_given? result = yield instance return result end instance end - def self.create(filename) - self.new(filename, nil) + def self.create(filename, options={}) + self.new(filename, nil, options) end attr_reader :filename - def initialize(filename, io_stream) + def initialize(filename, io_stream, options={}) @filename = filename - @workbook = io_stream ? org.apache.poi.ss.usermodel.WorkbookFactory.create(io_stream) : org.apache.poi.xssf.usermodel.XSSFWorkbook.new + @workbook = if io_stream + org.apache.poi.ss.usermodel.WorkbookFactory.create(io_stream) + elsif options[:format] == :hssf + org.apache.poi.hssf.usermodel.HSSFWorkbook.new + else + org.apache.poi.xssf.usermodel.XSSFWorkbook.new + end end def formula_evaluator @formula_evaluator ||= @workbook.creation_helper.create_formula_evaluator end def save save_as(@filename) end def save_as(filename) output = output_stream filename begin @workbook.write(output) ensure output.close end end def output_stream name java.io.FileOutputStream.new(name) end def close #noop end def create_sheet name='New Sheet' # @workbook.createSheet name worksheets[name] end def create_style options={} font = @workbook.createFont set_value( font, :font_height_in_points, options ) do | value | value.to_i end set_value font, :bold_weight, options, FONT_CONSTANTS set_value font, :color, options, INDEXED_COLORS_CONSTANTS do | value | value.index end style = @workbook.createCellStyle [:alignment, :vertical_alignment, :fill_pattern, :border_right, :border_left, :border_top, :border_bottom].each do | sym | set_value style, sym, options, CELL_STYLE_CONSTANTS do | value | value.to_i end end [:right_border_color, :left_border_color, :top_border_color, :bottom_border_color, :fill_foreground_color, :fill_background_color].each do | sym | set_value( style, sym, options, INDEXED_COLORS_CONSTANTS ) do | value | value.index end end [:hidden, :locked, :wrap_text].each do | sym | set_value style, sym, options end [:rotation, :indentation].each do | sym | set_value( style, sym, options ) do | value | value.to_i end end set_value( style, :data_format, options ) do |value| @workbook.create_data_format.getFormat(value) end style.font = font style end def set_value on, value_sym, from, using=nil return on unless from.has_key?(value_sym) value = if using using[from[value_sym]] else from[value_sym] end value = yield value if block_given? on.send("set_#{value_sym}", value) on end def worksheets @worksheets ||= Worksheets.new(self) end def named_ranges @named_ranges ||= ([email protected]_of_names).collect do | idx | NamedRange.new @workbook.name_at(idx), self end end # reference can be a Fixnum, referring to the 0-based sheet or # a String which is the sheet name or a cell reference. # # If a cell reference is passed the value of that cell is returned. # # If the reference refers to a contiguous range of cells an Array of values will be returned. # # If the reference refers to a multiple columns a Hash of values will be returned by column name. def [](reference) if Fixnum === reference return worksheets[reference] end if sheet = worksheets.detect{|e| e.name == reference} return sheet.poi_worksheet.nil? ? nil : sheet end cell = cell(reference) if Array === cell cell.collect{|e| e.value} elsif Hash === cell values = {} cell.each_pair{|column_name, cells| values[column_name] = cells.collect{|e| e.value}} values else cell.value end end # takes a String in the form of a 3D cell reference and returns the Cell (eg. "Sheet 1!A1") # # If the reference refers to a contiguous range of cells an array of Cells will be returned def cell reference # if the reference is to a named range of cells, get that range and return it if named_range = named_ranges.detect{|e| e.name == reference} cells = named_range.cells.compact if cells.empty? return nil else return cells.length == 1 ? cells.first : cells end end # check if the named_range is a full column reference if column_reference?(named_range) return all_cells_in_column named_range.formula end # if the reference is to an area of cells, get all the cells in that area and return them cells = cells_in_area(reference) unless cells.empty? return cells.length == 1 ? cells.first : cells end if column_reference?(reference) return all_cells_in_column reference end ref = POI::CELL_REF.new(reference) single_cell ref end # ref is a POI::CELL_REF instance def single_cell ref if ref.sheet_name.nil? raise 'cell references at the workbook level must include a sheet reference (eg. Sheet1!A1)' else worksheets[ref.sheet_name][ref.row][ref.col] end end def cells_in_area reference area = Area.new(reference) area.in(self) end def poi_workbook @workbook end def on_update cell #clear_all_formula_results #formula_evaluator.notify_update_cell cell.poi_cell end def on_formula_update cell #clear_all_formula_results formula_evaluator.notify_set_formula cell.poi_cell formula_evaluator.evaluate_formula_cell(cell.poi_cell) end def on_delete cell #clear_all_formula_results formula_evaluator.notify_delete_cell cell.poi_cell end def clear_all_formula_results formula_evaluator.clear_all_cached_result_values end def all_cells_in_column reference sheet_parts = reference.split('!') area_parts = sheet_parts.last.split(':') area_start = "#{sheet_parts.first}!#{area_parts.first}" area_end = area_parts.last area = org.apache.poi.ss.util.AreaReference.getWholeColumn(area_start, area_end) full_ref = "#{area.first_cell.format_as_string}:#{area.last_cell.format_as_string}" Area.new(full_ref).in(self) # cell_reference = org.apache.poi.ss.util.CellReference.new( reference + "1" ) # column = cell_reference.get_col # sheet = cell_reference.get_sheet_name # worksheets[sheet].rows.collect{|row| row[column]} end private def column_reference? named_range_or_reference return false if named_range_or_reference.nil? reference = named_range_or_reference if NamedRange === named_range_or_reference reference = named_range_or_reference.formula end cell_reference = reference.split('!', 2).last beginning, ending = cell_reference.split(':') !(beginning =~ /\d/ || (ending.nil? ? false : ending =~ /\d/)) end end end diff --git a/spec/workbook_spec.rb b/spec/workbook_spec.rb index a18c427..f1675ab 100644 --- a/spec/workbook_spec.rb +++ b/spec/workbook_spec.rb @@ -1,370 +1,385 @@ require 'spec_helper' require 'date' require 'stringio' describe POI::Workbook do it "should open a workbook and allow access to its worksheets" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.worksheets.size.should == 5 book.filename.should == name end it "should be able to create a Workbook from an IO object" do content = StringIO.new(open(TestDataFile.expand_path("various_samples.xlsx"), 'rb'){|f| f.read}) book = POI::Workbook.open(content) book.worksheets.size.should == 5 book.filename.should =~ /spreadsheet.xlsx$/ end it "should be able to create a Workbook from a Java input stream" do content = java.io.FileInputStream.new(TestDataFile.expand_path("various_samples.xlsx")) book = POI::Workbook.open(content) book.worksheets.size.should == 5 book.filename.should =~ /spreadsheet.xlsx$/ end - + + it "should create an HSSFWorkbook when passed a :format => :hssf option" do + book = POI::Workbook.create('test.xls', :format => :hssf) + book.poi_workbook.should be_kind_of(org.apache.poi.hssf.usermodel.HSSFWorkbook) + end + + it "should create an XSSFWorkbook when passed a :format => :xssf option" do + book = POI::Workbook.create('test.xlsx', :format => :xssf) + book.poi_workbook.should be_kind_of(org.apache.poi.xssf.usermodel.XSSFWorkbook) + end + + it "should create an XSSFWorkbook by default" do + book = POI::Workbook.create('test.xlsx') + book.poi_workbook.should be_kind_of(org.apache.poi.xssf.usermodel.XSSFWorkbook) + end + it "should return a column of cells by reference" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book["numbers!$A"].should == book['numbers'].rows.collect{|e| e[0].value} book["numbers!A"].should == book['numbers'].rows.collect{|e| e[0].value} book["numbers!C"].should == book['numbers'].rows.collect{|e| e[2].value} book["numbers!$D:$D"].should == book['numbers'].rows.collect{|e| e[3].value} book["numbers!$c:$D"].should == {"C" => book['numbers'].rows.collect{|e| e[2].value}, "D" => book['numbers'].rows.collect{|e| e[3].value}} end it "should return cells by reference" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.cell("numbers!A1").value.should == 'NUM' book.cell("numbers!A2").to_s.should == '1.0' book.cell("numbers!A3").to_s.should == '2.0' book.cell("numbers!A4").to_s.should == '3.0' book.cell("numbers!A10").to_s.should == '9.0' book.cell("numbers!B10").to_s.should == '81.0' book.cell("numbers!C10").to_s.should == '729.0' book.cell("numbers!D10").to_s.should == '3.0' book.cell("text & pic!A10").value.should == 'This is an Excel XLSX workbook.' book.cell("bools & errors!B3").value.should == true book.cell("high refs!AM619").value.should == 'This is some text' book.cell("high refs!AO624").value.should == 24.0 book.cell("high refs!AP631").value.should == 13.0 book.cell(%Q{'text & pic'!A10}).value.should == 'This is an Excel XLSX workbook.' book.cell(%Q{'bools & errors'!B3}).value.should == true book.cell(%Q{'high refs'!AM619}).value.should == 'This is some text' book.cell(%Q{'high refs'!AO624}).value.should == 24.0 book.cell(%Q{'high refs'!AP631}).value.should == 13.0 end it "should handle named cell ranges" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.named_ranges.length.should == 3 book.named_ranges.collect{|e| e.name}.should == %w{four_times_six NAMES nums} book.named_ranges.collect{|e| e.sheet.name}.should == ['high refs', 'bools & errors', 'high refs'] book.named_ranges.collect{|e| e.formula}.should == ["'high refs'!$AO$624", "'bools & errors'!$D$2:$D$11", "'high refs'!$AP$619:$AP$631"] book['four_times_six'].should == 24.0 book['nums'].should == (1..13).collect{|e| e * 1.0} # NAMES is a range of empty cells book['NAMES'].should == [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil] book.cell('NAMES').each do | cell | cell.value.should be_nil cell.poi_cell.should_not be_nil cell.to_s.should be_empty end end it "should return an array of cell values by reference" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book['dates!A2:A16'].should == (Date.parse('2010-02-28')..Date.parse('2010-03-14')).to_a end it "should return cell values by reference" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book['text & pic!A10'].should == 'This is an Excel XLSX workbook.' book['bools & errors!B3'].should == true book['high refs!AM619'].should == 'This is some text' book['high refs!AO624'].should == 24.0 book['high refs!AP631'].should == 13.0 end end describe POI::Worksheets do it "should allow indexing worksheets by ordinal" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.worksheets[0].name.should == "text & pic" book.worksheets[1].name.should == "numbers" book.worksheets[2].name.should == "dates" book.worksheets[3].name.should == "bools & errors" end it "should allow indexing worksheets by name" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.worksheets["text & pic"].name.should == "text & pic" book.worksheets["numbers"].name.should == "numbers" book.worksheets["dates"].name.should == "dates" end it "should be enumerable" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.worksheets.should be_kind_of Enumerable book.worksheets.each do |sheet| sheet.should be_kind_of POI::Worksheet end book.worksheets.count.should == 5 book.worksheets.collect.count.should == 5 end it "returns cells when passing a cell reference" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book['dates']['A2'].to_s.should == '2010-02-28' book['dates']['a2'].to_s.should == '2010-02-28' book['dates']['B2'].to_s.should == '2010-03-14' book['dates']['b2'].to_s.should == '2010-03-14' book['dates']['C2'].to_s.should == '2010-03-28' book['dates']['c2'].to_s.should == '2010-03-28' end end describe POI::Rows do it "should be enumerable" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) sheet = book.worksheets["text & pic"] sheet.rows.should be_kind_of Enumerable sheet.rows.each do |row| row.should be_kind_of POI::Row end sheet.rows.count.should == 7 sheet.rows.collect.count.should == 7 end end describe POI::Cells do before :each do @name = TestDataFile.expand_path("various_samples.xlsx") @book = POI::Workbook.open(@name) end def book @book end def name @name end it "should be enumerable" do sheet = book.worksheets["text & pic"] rows = sheet.rows cells = rows[0].cells cells.should be_kind_of Enumerable cells.count.should == 1 cells.collect.count.should == 1 end end describe POI::Cell do before :each do @name = TestDataFile.expand_path("various_samples.xlsx") @book = POI::Workbook.open(@name) end def book @book end def name @name end it "should provide dates for date cells" do sheet = book.worksheets["dates"] rows = sheet.rows dates_by_column = [ (Date.parse('2010-02-28')..Date.parse('2010-03-14')), (Date.parse('2010-03-14')..Date.parse('2010-03-28')), (Date.parse('2010-03-28')..Date.parse('2010-04-11'))] (0..2).each do |col| dates_by_column[col].each_with_index do |date, index| row = index + 1 rows[row][col].value.should equal_at_cell(date, row, col) end end end it "should provide numbers for numeric cells" do sheet = book.worksheets["numbers"] rows = sheet.rows (1..15).each do |number| row = number rows[row][0].value.should equal_at_cell(number, row, 0) rows[row][1].value.should equal_at_cell(number ** 2, row, 1) rows[row][2].value.should equal_at_cell(number ** 3, row, 2) rows[row][3].value.should equal_at_cell(Math.sqrt(number), row, 3) end rows[9][0].to_s.should == '9.0' rows[9][1].to_s.should == '81.0' rows[9][2].to_s.should == '729.0' rows[9][3].to_s.should == '3.0' end it "should handle array access from the workbook down to cells" do book[1][9][0].to_s.should == '9.0' book[1][9][1].to_s.should == '81.0' book[1][9][2].to_s.should == '729.0' book[1][9][3].to_s.should == '3.0' book["numbers"][9][0].to_s.should == '9.0' book["numbers"][9][1].to_s.should == '81.0' book["numbers"][9][2].to_s.should == '729.0' book["numbers"][9][3].to_s.should == '3.0' end it "should provide error text for error cells" do sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[6][0].value.should == 0.0 #'~CIRCULAR~REF~' rows[6][0].error_value.should be_nil rows[7][0].value.should be_nil rows[7][0].error_value.should == '#DIV/0!' rows[8][0].value.should be_nil rows[8][0].error_value.should == '#N/A' rows[9][0].value.should be_nil rows[9][0].error_value.should == '#NAME?' rows[10][0].value.should be_nil rows[10][0].error_value.should == '#NULL!' rows[11][0].value.should be_nil rows[11][0].error_value.should == '#NUM!' rows[12][0].value.should be_nil rows[12][0].error_value.should == '#REF!' rows[13][0].value.should be_nil rows[13][0].error_value.should == '#VALUE!' lambda{ rows[14][0].value }.should_not raise_error(Java::java.lang.RuntimeException) rows[6][0].to_s.should == '0.0' #'~CIRCULAR~REF~' rows[7][0].to_s.should == '' #'#DIV/0!' rows[8][0].to_s.should == '' #'#N/A' rows[9][0].to_s.should == '' #'#NAME?' rows[10][0].to_s.should == '' #'#NULL!' rows[11][0].to_s.should == '' #'#NUM!' rows[12][0].to_s.should == '' #'#REF!' rows[13][0].to_s.should == '' #'#VALUE!' rows[14][0].to_s.should == '' end it "should provide booleans for boolean cells" do sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[1][0].value.should == false rows[1][0].to_s.should == 'false' rows[1][1].value.should == false rows[1][1].to_s.should == 'false' rows[2][0].value.should == true rows[2][0].to_s.should == 'true' rows[2][1].value.should == true rows[2][1].to_s.should == 'true' end it "should provide the cell value as a string" do sheet = book.worksheets["text & pic"] rows = sheet.rows rows[0][0].value.should == "This" rows[1][0].value.should == "is" rows[2][0].value.should == "an" rows[3][0].value.should == "Excel" rows[4][0].value.should == "XLSX" rows[5][0].value.should == "workbook" rows[9][0].value.should == 'This is an Excel XLSX workbook.' rows[0][0].to_s.should == "This" rows[1][0].to_s.should == "is" rows[2][0].to_s.should == "an" rows[3][0].to_s.should == "Excel" rows[4][0].to_s.should == "XLSX" rows[5][0].to_s.should == "workbook" rows[9][0].to_s.should == 'This is an Excel XLSX workbook.' end it "should provide formulas instead of string-ified values" do sheet = book.worksheets["numbers"] rows = sheet.rows (1..15).each do |number| row = number rows[row][0].to_s(false).should == "#{number}.0" rows[row][1].to_s(false).should == "A#{row + 1}*A#{row + 1}" rows[row][2].to_s(false).should == "B#{row + 1}*A#{row + 1}" rows[row][3].to_s(false).should == "SQRT(A#{row + 1})" end sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[1][0].to_s(false).should == '1=2' rows[1][1].to_s(false).should == 'FALSE' rows[2][0].to_s(false).should == '1=1' rows[2][1].to_s(false).should == 'TRUE' rows[14][0].to_s(false).should == 'foobar(1)' sheet = book.worksheets["text & pic"] sheet.rows[9][0].to_s(false).should == 'CONCATENATE(A1," ", A2," ", A3," ", A4," ", A5," ", A6,".")' end it "should handle getting values out of 'non-existent' cells" do sheet = book.worksheets["bools & errors"] sheet.rows[14][2].value.should be_nil end it "should notify the workbook that I have been updated" do book['dates!A10'].to_s.should == '2010-03-08' book['dates!A16'].to_s.should == '2010-03-14' book['dates!B2'].to_s.should == '2010-03-14' cell = book.cell('dates!B2') cell.formula.should == 'A16' cell.formula = 'A10 + 1' book.cell('dates!B2').poi_cell.should === cell.poi_cell book.cell('dates!B2').formula.should == 'A10 + 1' book['dates!B2'].to_s.should == '2010-03-09' end end
kameeoze/jruby-poi
67e745c429a6877127dc7e7d3859cde52ff51553
Ruby 1.9 compatibility
diff --git a/.travis.yml b/.travis.yml index ffa0161..f8383ec 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,4 @@ -language: ruby -rvm: - - jruby-18mode +language: ruby +rvm: + - jruby-18mode + - jruby-19mode \ No newline at end of file diff --git a/lib/poi/workbook/area.rb b/lib/poi/workbook/area.rb index bb93e3f..e38f3b1 100644 --- a/lib/poi/workbook/area.rb +++ b/lib/poi/workbook/area.rb @@ -1,81 +1,81 @@ -module POI - class Area - def initialize reference - @ref = reference - end - - def in workbook - if single_cell_reference? - ref = area.all_referenced_cells.first - return [workbook.single_cell(ref)] - end - - begin - by_column = {} - # refs = area.all_referenced_cells - # slices = refs.enum_slice(refs.length/15) - # slices.collect do |cell_refs| - # Thread.start do - # cell_refs.each do |cell_ref| - # first = workbook.worksheets[cell_ref.sheet_name].first_row - # last = workbook.worksheets[cell_ref.sheet_name].last_row - # next unless cell_ref.row >= first && cell_ref.row <= last - # - # # ref = POI::CELL_REF.new(c.format_as_string) - # cell = workbook.single_cell cell_ref - # (by_column[cell_ref.cell_ref_parts.collect.last] ||= []) << cell - # end - # end - # end.each {|t| t.join} - - area.all_referenced_cells.each do |cell_ref| - first = workbook.worksheets[cell_ref.sheet_name].first_row - last = workbook.worksheets[cell_ref.sheet_name].last_row - next unless cell_ref.row >= first && cell_ref.row <= last - - # ref = POI::CELL_REF.new(c.format_as_string) - cell = workbook.single_cell cell_ref - (by_column[cell_ref.cell_ref_parts.collect.last] ||= []) << cell - end - - by_column.each do |key, cells| - by_column[key] = cells.compact - end - - if by_column.length == 1 - by_column.values.flatten - else - by_column - end - rescue - [] - end - end - - def single_cell_reference? - area.single_cell? #@ref == getFirstCell.formatAsString rescue false - end - - private - def area - @area ||= new_area_reference - end - - def new_area_reference - begin - return POI::AREA_REF.new(@ref) - rescue - # not a valid reference, so proceed through to see if it's a column-based reference - end - sheet_parts = @ref.split('!') - area_parts = sheet_parts.last.split(':') - area_start = "#{sheet_parts.first}!#{area_parts.first}" - area_end = area_parts.last - begin - POI::AREA_REF.getWholeColumn(area_start, area_end) - rescue - raise "could not determine area reference for #{@ref}: #{$!.message}" - end - end - end -end +module POI + class Area + def initialize reference + @ref = reference + end + + def in workbook + if single_cell_reference? + ref = area.all_referenced_cells.first + return [workbook.single_cell(ref)] + end + + begin + by_column = {} + # refs = area.all_referenced_cells + # slices = refs.enum_slice(refs.length/15) + # slices.collect do |cell_refs| + # Thread.start do + # cell_refs.each do |cell_ref| + # first = workbook.worksheets[cell_ref.sheet_name].first_row + # last = workbook.worksheets[cell_ref.sheet_name].last_row + # next unless cell_ref.row >= first && cell_ref.row <= last + # + # # ref = POI::CELL_REF.new(c.format_as_string) + # cell = workbook.single_cell cell_ref + # (by_column[cell_ref.cell_ref_parts.collect.last] ||= []) << cell + # end + # end + # end.each {|t| t.join} + + area.all_referenced_cells.each do |cell_ref| + first = workbook.worksheets[cell_ref.sheet_name].first_row + last = workbook.worksheets[cell_ref.sheet_name].last_row + next unless cell_ref.row >= first && cell_ref.row <= last + + # ref = POI::CELL_REF.new(c.format_as_string) + cell = workbook.single_cell cell_ref + (by_column[cell_ref.cell_ref_parts.to_a.last] ||= []) << cell + end + + by_column.each do |key, cells| + by_column[key] = cells.compact + end + + if by_column.length == 1 + by_column.values.flatten + else + by_column + end + rescue + [] + end + end + + def single_cell_reference? + area.single_cell? #@ref == getFirstCell.formatAsString rescue false + end + + private + def area + @area ||= new_area_reference + end + + def new_area_reference + begin + return POI::AREA_REF.new(@ref) + rescue + # not a valid reference, so proceed through to see if it's a column-based reference + end + sheet_parts = @ref.split('!') + area_parts = sheet_parts.last.split(':') + area_start = "#{sheet_parts.first}!#{area_parts.first}" + area_end = area_parts.last + begin + POI::AREA_REF.getWholeColumn(area_start, area_end) + rescue + raise "could not determine area reference for #{@ref}: #{$!.message}" + end + end + end +end diff --git a/spec/workbook_spec.rb b/spec/workbook_spec.rb index e816f27..a18c427 100644 --- a/spec/workbook_spec.rb +++ b/spec/workbook_spec.rb @@ -1,370 +1,370 @@ -require 'spec_helper' - -require 'date' -require 'stringio' - -describe POI::Workbook do - it "should open a workbook and allow access to its worksheets" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) - book.worksheets.size.should == 5 - book.filename.should == name - end - - it "should be able to create a Workbook from an IO object" do - content = StringIO.new(open(TestDataFile.expand_path("various_samples.xlsx"), 'rb'){|f| f.read}) - book = POI::Workbook.open(content) - book.worksheets.size.should == 5 - book.filename.should =~ /spreadsheet.xlsx$/ - end - - it "should be able to create a Workbook from a Java input stream" do - content = java.io.FileInputStream.new(TestDataFile.expand_path("various_samples.xlsx")) - book = POI::Workbook.open(content) - book.worksheets.size.should == 5 - book.filename.should =~ /spreadsheet.xlsx$/ - end - - it "should return a column of cells by reference" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) - book["numbers!$A"].should == book['numbers'].rows.collect{|e| e[0].value} - book["numbers!A"].should == book['numbers'].rows.collect{|e| e[0].value} - book["numbers!C"].should == book['numbers'].rows.collect{|e| e[2].value} - book["numbers!$D:$D"].should == book['numbers'].rows.collect{|e| e[3].value} - book["numbers!$c:$D"].should == {"C" => book['numbers'].rows.collect{|e| e[2].value}, "D" => book['numbers'].rows.collect{|e| e[3].value}} - end - - it "should return cells by reference" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) - book.cell("numbers!A1").value.should == 'NUM' - book.cell("numbers!A2").to_s.should == '1.0' - book.cell("numbers!A3").to_s.should == '2.0' - book.cell("numbers!A4").to_s.should == '3.0' - - book.cell("numbers!A10").to_s.should == '9.0' - book.cell("numbers!B10").to_s.should == '81.0' - book.cell("numbers!C10").to_s.should == '729.0' - book.cell("numbers!D10").to_s.should == '3.0' - - book.cell("text & pic!A10").value.should == 'This is an Excel XLSX workbook.' - book.cell("bools & errors!B3").value.should == true - book.cell("high refs!AM619").value.should == 'This is some text' - book.cell("high refs!AO624").value.should == 24.0 - book.cell("high refs!AP631").value.should == 13.0 - - book.cell(%Q{'text & pic'!A10}).value.should == 'This is an Excel XLSX workbook.' - book.cell(%Q{'bools & errors'!B3}).value.should == true - book.cell(%Q{'high refs'!AM619}).value.should == 'This is some text' - book.cell(%Q{'high refs'!AO624}).value.should == 24.0 - book.cell(%Q{'high refs'!AP631}).value.should == 13.0 - end - - it "should handle named cell ranges" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) - - book.named_ranges.length.should == 3 - book.named_ranges.collect{|e| e.name}.should == %w{four_times_six NAMES nums} - book.named_ranges.collect{|e| e.sheet.name}.should == ['high refs', 'bools & errors', 'high refs'] - book.named_ranges.collect{|e| e.formula}.should == ["'high refs'!$AO$624", "'bools & errors'!$D$2:$D$11", "'high refs'!$AP$619:$AP$631"] - book['four_times_six'].should == 24.0 - book['nums'].should == (1..13).collect{|e| e * 1.0} - - # NAMES is a range of empty cells - book['NAMES'].should == [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil] - book.cell('NAMES').each do | cell | - cell.value.should be_nil - cell.poi_cell.should_not be_nil - cell.to_s.should be_empty - end - end - - it "should return an array of cell values by reference" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) - book['dates!A2:A16'].should == (Date.parse('2010-02-28')..Date.parse('2010-03-14')).to_a - end - - it "should return cell values by reference" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) - - book['text & pic!A10'].should == 'This is an Excel XLSX workbook.' - book['bools & errors!B3'].should == true - book['high refs!AM619'].should == 'This is some text' - book['high refs!AO624'].should == 24.0 - book['high refs!AP631'].should == 13.0 - end -end - -describe POI::Worksheets do - it "should allow indexing worksheets by ordinal" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) - - book.worksheets[0].name.should == "text & pic" - book.worksheets[1].name.should == "numbers" - book.worksheets[2].name.should == "dates" - book.worksheets[3].name.should == "bools & errors" - end - - it "should allow indexing worksheets by name" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) - - book.worksheets["text & pic"].name.should == "text & pic" - book.worksheets["numbers"].name.should == "numbers" - book.worksheets["dates"].name.should == "dates" - end - - it "should be enumerable" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) - book.worksheets.should be_kind_of Enumerable - - book.worksheets.each do |sheet| - sheet.should be_kind_of POI::Worksheet - end - - book.worksheets.size.should == 5 - book.worksheets.collect.size.should == 5 - end - - it "returns cells when passing a cell reference" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) - book['dates']['A2'].to_s.should == '2010-02-28' - book['dates']['a2'].to_s.should == '2010-02-28' - book['dates']['B2'].to_s.should == '2010-03-14' - book['dates']['b2'].to_s.should == '2010-03-14' - book['dates']['C2'].to_s.should == '2010-03-28' - book['dates']['c2'].to_s.should == '2010-03-28' - end -end - -describe POI::Rows do - it "should be enumerable" do - name = TestDataFile.expand_path("various_samples.xlsx") - book = POI::Workbook.open(name) - sheet = book.worksheets["text & pic"] - sheet.rows.should be_kind_of Enumerable - - sheet.rows.each do |row| - row.should be_kind_of POI::Row - end - - sheet.rows.size.should == 7 - sheet.rows.collect.size.should == 7 - end -end - -describe POI::Cells do - before :each do - @name = TestDataFile.expand_path("various_samples.xlsx") - @book = POI::Workbook.open(@name) - end - - def book - @book - end - - def name - @name - end - - it "should be enumerable" do - sheet = book.worksheets["text & pic"] - rows = sheet.rows - cells = rows[0].cells - - cells.should be_kind_of Enumerable - cells.size.should == 1 - cells.collect.size.should == 1 - end -end - -describe POI::Cell do - before :each do - @name = TestDataFile.expand_path("various_samples.xlsx") - @book = POI::Workbook.open(@name) - end - - def book - @book - end - - def name - @name - end - - it "should provide dates for date cells" do - sheet = book.worksheets["dates"] - rows = sheet.rows - - dates_by_column = [ - (Date.parse('2010-02-28')..Date.parse('2010-03-14')), - (Date.parse('2010-03-14')..Date.parse('2010-03-28')), - (Date.parse('2010-03-28')..Date.parse('2010-04-11'))] - (0..2).each do |col| - dates_by_column[col].each_with_index do |date, index| - row = index + 1 - rows[row][col].value.should equal_at_cell(date, row, col) - end - end - end - - it "should provide numbers for numeric cells" do - sheet = book.worksheets["numbers"] - rows = sheet.rows - - (1..15).each do |number| - row = number - rows[row][0].value.should equal_at_cell(number, row, 0) - rows[row][1].value.should equal_at_cell(number ** 2, row, 1) - rows[row][2].value.should equal_at_cell(number ** 3, row, 2) - rows[row][3].value.should equal_at_cell(Math.sqrt(number), row, 3) - end - - rows[9][0].to_s.should == '9.0' - rows[9][1].to_s.should == '81.0' - rows[9][2].to_s.should == '729.0' - rows[9][3].to_s.should == '3.0' - end - - it "should handle array access from the workbook down to cells" do - book[1][9][0].to_s.should == '9.0' - book[1][9][1].to_s.should == '81.0' - book[1][9][2].to_s.should == '729.0' - book[1][9][3].to_s.should == '3.0' - - book["numbers"][9][0].to_s.should == '9.0' - book["numbers"][9][1].to_s.should == '81.0' - book["numbers"][9][2].to_s.should == '729.0' - book["numbers"][9][3].to_s.should == '3.0' - end - - it "should provide error text for error cells" do - sheet = book.worksheets["bools & errors"] - rows = sheet.rows - - rows[6][0].value.should == 0.0 #'~CIRCULAR~REF~' - rows[6][0].error_value.should be_nil - - rows[7][0].value.should be_nil - rows[7][0].error_value.should == '#DIV/0!' - - rows[8][0].value.should be_nil - rows[8][0].error_value.should == '#N/A' - - rows[9][0].value.should be_nil - rows[9][0].error_value.should == '#NAME?' - - rows[10][0].value.should be_nil - rows[10][0].error_value.should == '#NULL!' - - rows[11][0].value.should be_nil - rows[11][0].error_value.should == '#NUM!' - - rows[12][0].value.should be_nil - rows[12][0].error_value.should == '#REF!' - - rows[13][0].value.should be_nil - rows[13][0].error_value.should == '#VALUE!' - - lambda{ rows[14][0].value }.should_not raise_error(Java::java.lang.RuntimeException) - - rows[6][0].to_s.should == '0.0' #'~CIRCULAR~REF~' - rows[7][0].to_s.should == '' #'#DIV/0!' - rows[8][0].to_s.should == '' #'#N/A' - rows[9][0].to_s.should == '' #'#NAME?' - rows[10][0].to_s.should == '' #'#NULL!' - rows[11][0].to_s.should == '' #'#NUM!' - rows[12][0].to_s.should == '' #'#REF!' - rows[13][0].to_s.should == '' #'#VALUE!' - rows[14][0].to_s.should == '' - end - - it "should provide booleans for boolean cells" do - sheet = book.worksheets["bools & errors"] - rows = sheet.rows - rows[1][0].value.should == false - rows[1][0].to_s.should == 'false' - - rows[1][1].value.should == false - rows[1][1].to_s.should == 'false' - - rows[2][0].value.should == true - rows[2][0].to_s.should == 'true' - - rows[2][1].value.should == true - rows[2][1].to_s.should == 'true' - end - - it "should provide the cell value as a string" do - sheet = book.worksheets["text & pic"] - rows = sheet.rows - - rows[0][0].value.should == "This" - rows[1][0].value.should == "is" - rows[2][0].value.should == "an" - rows[3][0].value.should == "Excel" - rows[4][0].value.should == "XLSX" - rows[5][0].value.should == "workbook" - rows[9][0].value.should == 'This is an Excel XLSX workbook.' - - - rows[0][0].to_s.should == "This" - rows[1][0].to_s.should == "is" - rows[2][0].to_s.should == "an" - rows[3][0].to_s.should == "Excel" - rows[4][0].to_s.should == "XLSX" - rows[5][0].to_s.should == "workbook" - rows[9][0].to_s.should == 'This is an Excel XLSX workbook.' - end - - it "should provide formulas instead of string-ified values" do - sheet = book.worksheets["numbers"] - rows = sheet.rows - - (1..15).each do |number| - row = number - rows[row][0].to_s(false).should == "#{number}.0" - rows[row][1].to_s(false).should == "A#{row + 1}*A#{row + 1}" - rows[row][2].to_s(false).should == "B#{row + 1}*A#{row + 1}" - rows[row][3].to_s(false).should == "SQRT(A#{row + 1})" - end - - sheet = book.worksheets["bools & errors"] - rows = sheet.rows - rows[1][0].to_s(false).should == '1=2' - rows[1][1].to_s(false).should == 'FALSE' - rows[2][0].to_s(false).should == '1=1' - rows[2][1].to_s(false).should == 'TRUE' - rows[14][0].to_s(false).should == 'foobar(1)' - - sheet = book.worksheets["text & pic"] - sheet.rows[9][0].to_s(false).should == 'CONCATENATE(A1," ", A2," ", A3," ", A4," ", A5," ", A6,".")' - end - - it "should handle getting values out of 'non-existent' cells" do - sheet = book.worksheets["bools & errors"] - sheet.rows[14][2].value.should be_nil - end - - it "should notify the workbook that I have been updated" do - book['dates!A10'].to_s.should == '2010-03-08' - book['dates!A16'].to_s.should == '2010-03-14' - book['dates!B2'].to_s.should == '2010-03-14' - - cell = book.cell('dates!B2') - cell.formula.should == 'A16' - - cell.formula = 'A10 + 1' - book.cell('dates!B2').poi_cell.should === cell.poi_cell - book.cell('dates!B2').formula.should == 'A10 + 1' - - book['dates!B2'].to_s.should == '2010-03-09' - end -end +require 'spec_helper' + +require 'date' +require 'stringio' + +describe POI::Workbook do + it "should open a workbook and allow access to its worksheets" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + book.worksheets.size.should == 5 + book.filename.should == name + end + + it "should be able to create a Workbook from an IO object" do + content = StringIO.new(open(TestDataFile.expand_path("various_samples.xlsx"), 'rb'){|f| f.read}) + book = POI::Workbook.open(content) + book.worksheets.size.should == 5 + book.filename.should =~ /spreadsheet.xlsx$/ + end + + it "should be able to create a Workbook from a Java input stream" do + content = java.io.FileInputStream.new(TestDataFile.expand_path("various_samples.xlsx")) + book = POI::Workbook.open(content) + book.worksheets.size.should == 5 + book.filename.should =~ /spreadsheet.xlsx$/ + end + + it "should return a column of cells by reference" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + book["numbers!$A"].should == book['numbers'].rows.collect{|e| e[0].value} + book["numbers!A"].should == book['numbers'].rows.collect{|e| e[0].value} + book["numbers!C"].should == book['numbers'].rows.collect{|e| e[2].value} + book["numbers!$D:$D"].should == book['numbers'].rows.collect{|e| e[3].value} + book["numbers!$c:$D"].should == {"C" => book['numbers'].rows.collect{|e| e[2].value}, "D" => book['numbers'].rows.collect{|e| e[3].value}} + end + + it "should return cells by reference" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + book.cell("numbers!A1").value.should == 'NUM' + book.cell("numbers!A2").to_s.should == '1.0' + book.cell("numbers!A3").to_s.should == '2.0' + book.cell("numbers!A4").to_s.should == '3.0' + + book.cell("numbers!A10").to_s.should == '9.0' + book.cell("numbers!B10").to_s.should == '81.0' + book.cell("numbers!C10").to_s.should == '729.0' + book.cell("numbers!D10").to_s.should == '3.0' + + book.cell("text & pic!A10").value.should == 'This is an Excel XLSX workbook.' + book.cell("bools & errors!B3").value.should == true + book.cell("high refs!AM619").value.should == 'This is some text' + book.cell("high refs!AO624").value.should == 24.0 + book.cell("high refs!AP631").value.should == 13.0 + + book.cell(%Q{'text & pic'!A10}).value.should == 'This is an Excel XLSX workbook.' + book.cell(%Q{'bools & errors'!B3}).value.should == true + book.cell(%Q{'high refs'!AM619}).value.should == 'This is some text' + book.cell(%Q{'high refs'!AO624}).value.should == 24.0 + book.cell(%Q{'high refs'!AP631}).value.should == 13.0 + end + + it "should handle named cell ranges" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + + book.named_ranges.length.should == 3 + book.named_ranges.collect{|e| e.name}.should == %w{four_times_six NAMES nums} + book.named_ranges.collect{|e| e.sheet.name}.should == ['high refs', 'bools & errors', 'high refs'] + book.named_ranges.collect{|e| e.formula}.should == ["'high refs'!$AO$624", "'bools & errors'!$D$2:$D$11", "'high refs'!$AP$619:$AP$631"] + book['four_times_six'].should == 24.0 + book['nums'].should == (1..13).collect{|e| e * 1.0} + + # NAMES is a range of empty cells + book['NAMES'].should == [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil] + book.cell('NAMES').each do | cell | + cell.value.should be_nil + cell.poi_cell.should_not be_nil + cell.to_s.should be_empty + end + end + + it "should return an array of cell values by reference" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + book['dates!A2:A16'].should == (Date.parse('2010-02-28')..Date.parse('2010-03-14')).to_a + end + + it "should return cell values by reference" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + + book['text & pic!A10'].should == 'This is an Excel XLSX workbook.' + book['bools & errors!B3'].should == true + book['high refs!AM619'].should == 'This is some text' + book['high refs!AO624'].should == 24.0 + book['high refs!AP631'].should == 13.0 + end +end + +describe POI::Worksheets do + it "should allow indexing worksheets by ordinal" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + + book.worksheets[0].name.should == "text & pic" + book.worksheets[1].name.should == "numbers" + book.worksheets[2].name.should == "dates" + book.worksheets[3].name.should == "bools & errors" + end + + it "should allow indexing worksheets by name" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + + book.worksheets["text & pic"].name.should == "text & pic" + book.worksheets["numbers"].name.should == "numbers" + book.worksheets["dates"].name.should == "dates" + end + + it "should be enumerable" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + book.worksheets.should be_kind_of Enumerable + + book.worksheets.each do |sheet| + sheet.should be_kind_of POI::Worksheet + end + + book.worksheets.count.should == 5 + book.worksheets.collect.count.should == 5 + end + + it "returns cells when passing a cell reference" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + book['dates']['A2'].to_s.should == '2010-02-28' + book['dates']['a2'].to_s.should == '2010-02-28' + book['dates']['B2'].to_s.should == '2010-03-14' + book['dates']['b2'].to_s.should == '2010-03-14' + book['dates']['C2'].to_s.should == '2010-03-28' + book['dates']['c2'].to_s.should == '2010-03-28' + end +end + +describe POI::Rows do + it "should be enumerable" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + sheet = book.worksheets["text & pic"] + sheet.rows.should be_kind_of Enumerable + + sheet.rows.each do |row| + row.should be_kind_of POI::Row + end + + sheet.rows.count.should == 7 + sheet.rows.collect.count.should == 7 + end +end + +describe POI::Cells do + before :each do + @name = TestDataFile.expand_path("various_samples.xlsx") + @book = POI::Workbook.open(@name) + end + + def book + @book + end + + def name + @name + end + + it "should be enumerable" do + sheet = book.worksheets["text & pic"] + rows = sheet.rows + cells = rows[0].cells + + cells.should be_kind_of Enumerable + cells.count.should == 1 + cells.collect.count.should == 1 + end +end + +describe POI::Cell do + before :each do + @name = TestDataFile.expand_path("various_samples.xlsx") + @book = POI::Workbook.open(@name) + end + + def book + @book + end + + def name + @name + end + + it "should provide dates for date cells" do + sheet = book.worksheets["dates"] + rows = sheet.rows + + dates_by_column = [ + (Date.parse('2010-02-28')..Date.parse('2010-03-14')), + (Date.parse('2010-03-14')..Date.parse('2010-03-28')), + (Date.parse('2010-03-28')..Date.parse('2010-04-11'))] + (0..2).each do |col| + dates_by_column[col].each_with_index do |date, index| + row = index + 1 + rows[row][col].value.should equal_at_cell(date, row, col) + end + end + end + + it "should provide numbers for numeric cells" do + sheet = book.worksheets["numbers"] + rows = sheet.rows + + (1..15).each do |number| + row = number + rows[row][0].value.should equal_at_cell(number, row, 0) + rows[row][1].value.should equal_at_cell(number ** 2, row, 1) + rows[row][2].value.should equal_at_cell(number ** 3, row, 2) + rows[row][3].value.should equal_at_cell(Math.sqrt(number), row, 3) + end + + rows[9][0].to_s.should == '9.0' + rows[9][1].to_s.should == '81.0' + rows[9][2].to_s.should == '729.0' + rows[9][3].to_s.should == '3.0' + end + + it "should handle array access from the workbook down to cells" do + book[1][9][0].to_s.should == '9.0' + book[1][9][1].to_s.should == '81.0' + book[1][9][2].to_s.should == '729.0' + book[1][9][3].to_s.should == '3.0' + + book["numbers"][9][0].to_s.should == '9.0' + book["numbers"][9][1].to_s.should == '81.0' + book["numbers"][9][2].to_s.should == '729.0' + book["numbers"][9][3].to_s.should == '3.0' + end + + it "should provide error text for error cells" do + sheet = book.worksheets["bools & errors"] + rows = sheet.rows + + rows[6][0].value.should == 0.0 #'~CIRCULAR~REF~' + rows[6][0].error_value.should be_nil + + rows[7][0].value.should be_nil + rows[7][0].error_value.should == '#DIV/0!' + + rows[8][0].value.should be_nil + rows[8][0].error_value.should == '#N/A' + + rows[9][0].value.should be_nil + rows[9][0].error_value.should == '#NAME?' + + rows[10][0].value.should be_nil + rows[10][0].error_value.should == '#NULL!' + + rows[11][0].value.should be_nil + rows[11][0].error_value.should == '#NUM!' + + rows[12][0].value.should be_nil + rows[12][0].error_value.should == '#REF!' + + rows[13][0].value.should be_nil + rows[13][0].error_value.should == '#VALUE!' + + lambda{ rows[14][0].value }.should_not raise_error(Java::java.lang.RuntimeException) + + rows[6][0].to_s.should == '0.0' #'~CIRCULAR~REF~' + rows[7][0].to_s.should == '' #'#DIV/0!' + rows[8][0].to_s.should == '' #'#N/A' + rows[9][0].to_s.should == '' #'#NAME?' + rows[10][0].to_s.should == '' #'#NULL!' + rows[11][0].to_s.should == '' #'#NUM!' + rows[12][0].to_s.should == '' #'#REF!' + rows[13][0].to_s.should == '' #'#VALUE!' + rows[14][0].to_s.should == '' + end + + it "should provide booleans for boolean cells" do + sheet = book.worksheets["bools & errors"] + rows = sheet.rows + rows[1][0].value.should == false + rows[1][0].to_s.should == 'false' + + rows[1][1].value.should == false + rows[1][1].to_s.should == 'false' + + rows[2][0].value.should == true + rows[2][0].to_s.should == 'true' + + rows[2][1].value.should == true + rows[2][1].to_s.should == 'true' + end + + it "should provide the cell value as a string" do + sheet = book.worksheets["text & pic"] + rows = sheet.rows + + rows[0][0].value.should == "This" + rows[1][0].value.should == "is" + rows[2][0].value.should == "an" + rows[3][0].value.should == "Excel" + rows[4][0].value.should == "XLSX" + rows[5][0].value.should == "workbook" + rows[9][0].value.should == 'This is an Excel XLSX workbook.' + + + rows[0][0].to_s.should == "This" + rows[1][0].to_s.should == "is" + rows[2][0].to_s.should == "an" + rows[3][0].to_s.should == "Excel" + rows[4][0].to_s.should == "XLSX" + rows[5][0].to_s.should == "workbook" + rows[9][0].to_s.should == 'This is an Excel XLSX workbook.' + end + + it "should provide formulas instead of string-ified values" do + sheet = book.worksheets["numbers"] + rows = sheet.rows + + (1..15).each do |number| + row = number + rows[row][0].to_s(false).should == "#{number}.0" + rows[row][1].to_s(false).should == "A#{row + 1}*A#{row + 1}" + rows[row][2].to_s(false).should == "B#{row + 1}*A#{row + 1}" + rows[row][3].to_s(false).should == "SQRT(A#{row + 1})" + end + + sheet = book.worksheets["bools & errors"] + rows = sheet.rows + rows[1][0].to_s(false).should == '1=2' + rows[1][1].to_s(false).should == 'FALSE' + rows[2][0].to_s(false).should == '1=1' + rows[2][1].to_s(false).should == 'TRUE' + rows[14][0].to_s(false).should == 'foobar(1)' + + sheet = book.worksheets["text & pic"] + sheet.rows[9][0].to_s(false).should == 'CONCATENATE(A1," ", A2," ", A3," ", A4," ", A5," ", A6,".")' + end + + it "should handle getting values out of 'non-existent' cells" do + sheet = book.worksheets["bools & errors"] + sheet.rows[14][2].value.should be_nil + end + + it "should notify the workbook that I have been updated" do + book['dates!A10'].to_s.should == '2010-03-08' + book['dates!A16'].to_s.should == '2010-03-14' + book['dates!B2'].to_s.should == '2010-03-14' + + cell = book.cell('dates!B2') + cell.formula.should == 'A16' + + cell.formula = 'A10 + 1' + book.cell('dates!B2').poi_cell.should === cell.poi_cell + book.cell('dates!B2').formula.should == 'A10 + 1' + + book['dates!B2'].to_s.should == '2010-03-09' + end +end diff --git a/spec/writing_spec.rb b/spec/writing_spec.rb index d8fea48..843e730 100644 --- a/spec/writing_spec.rb +++ b/spec/writing_spec.rb @@ -1,146 +1,144 @@ -require 'spec_helper' - -require 'date' -require 'stringio' - -describe "writing Workbooks" do - it "should create a new empty workbook" do - name = 'new-workbook.xlsx' - book = POI::Workbook.create(name) - book.should_not be_nil - end - - it "should create a new workbook and write something to it" do - name = TestDataFile.expand_path("timesheet-#{Time.now.strftime('%Y%m%d%H%M%S%s')}.xlsx") - create_timesheet_spreadsheet(name) - book = POI::Workbook.open(name) - book.worksheets.size.should == 1 - book.worksheets[0].name.should == 'Timesheet' - book.filename.should == name - book['Timesheet!A3'].should == 'Yegor Kozlov' - book.cell('Timesheet!J13').formula_value.should == 'SUM(J3:J12)' - FileUtils.rm_f name - end - - def create_timesheet_spreadsheet name='spec/data/timesheet.xlsx' - titles = ["Person", "ID", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Total\nHrs", "Overtime\nHrs", "Regular\nHrs"] - sample_data = [ - ["Yegor Kozlov", "YK", 5.0, 8.0, 10.0, 5.0, 5.0, 7.0, 6.0], - ["Gisella Bronzetti", "GB", 4.0, 3.0, 1.0, 3.5, nil, nil, 4.0] - ] - - book = POI::Workbook.create(name) - title_style = book.create_style :font_height_in_points => 18, :boldweight => :boldweight_bold, - :alignment => :align_center, :vertical_alignment => :vertical_center - header_style = book.create_style :font_height_in_points => 11, :color => :white, :fill_foreground_color => :grey_50_percent, - :fill_pattern => :solid_foreground, :alignment => :align_center, :vertical_alignment => :vertical_center - cell_style = book.create_style :alignment => :align_center, :border_bottom => :border_thin, :border_top => :border_thin, - :border_left => :border_thin, :border_right => :border_thin, :bottom_border_color => :black, - :right_border_color => :black, :left_border_color => :black, :top_border_color => :black - form1_style = book.create_style :data_format => '0.00', :fill_pattern => :solid_foreground, :fill_foreground_color => :grey_25_percent, - :alignment => :align_center, :vertical_alignment => :vertical_center - form2_style = book.create_style :data_format => '0.00', :fill_pattern => :solid_foreground, :fill_foreground_color => :grey_40_percent, - :alignment => :align_center, :vertical_alignment => :vertical_center - - sheet = book.create_sheet 'Timesheet' - print_setup = sheet.print_setup - print_setup.landscape = true - sheet.fit_to_page = true - sheet.horizontally_center = true - - title_row = sheet.rows[0] - title_row.height_in_points = 45 - title_cell = title_row.cells[0] - title_cell.value = 'Weekly Timesheet' - title_cell.style = title_style - sheet.add_merged_region org.apache.poi.ss.util.CellRangeAddress.valueOf("$A$1:$L$1") - - header_row = sheet[1] - header_row.height_in_points = 40 - titles.each_with_index do | title, index | - header_cell = header_row[index] - header_cell.value = title - header_cell.style = header_style - end - - row_num = 2 - 10.times do - row = sheet[row_num] - row_num += 1 - titles.each_with_index do | title, index | - cell = row[index] - if index == 9 - cell.formula = "SUM(C#{row_num}:I#{row_num})" - cell.style = form1_style - elsif index == 11 - cell.formula = "J#{row_num} - K#{row_num}" - cell.style = form1_style - else - cell.style = cell_style - end - end - end - - # row with totals below - sum_row = sheet[row_num] - row_num += 1 - sum_row.height_in_points = 35 - cell = sum_row[0] - cell.style = form1_style - cell = sum_row[1] - cell.style = form1_style - cell.value = 'Total Hrs:' - (2...12).each do | cell_index | - cell = sum_row[cell_index] - column = (?A + cell_index).chr - cell.formula = "SUM(#{column}3:#{column}12)" - if cell_index > 9 - cell.style = form2_style - else - cell.style = form1_style - end - end - row_num += 1 - sum_row = sheet[row_num] - row_num += 1 - sum_row.height_in_points = 25 - cell = sum_row[0] - cell.value = 'Total Regular Hours' - cell.style = form1_style - cell = sum_row[1] - cell.formula = 'L13' - cell.style = form2_style - sum_row = sheet[row_num] - row_num += 1 - cell = sum_row[0] - cell.value = 'Total Overtime Hours' - cell.style = form1_style - cell = sum_row[1] - cell.formula = 'K13' - cell.style = form2_style - - # set sample data - sample_data.each_with_index do |each, row_index| - row = sheet[2 + row_index] - each.each_with_index do | data, cell_index | - data = sample_data[row_index][cell_index] - next unless data - if data.kind_of? String - row[cell_index].value = data #.to_java(:string) - else - row[cell_index].value = data #.to_java(:double) - end - end - end - - # finally set column widths, the width is measured in units of 1/256th of a character width - sheet.set_column_width 0, 30*256 # 30 characters wide - (2..9).to_a.each do | column | - sheet.set_column_width column, 6*256 # 6 characters wide - end - sheet.set_column_width 10, 10*256 # 10 characters wide - - book.save - File.exist?(name).should == true - end -end +require 'date' +require 'stringio' + +describe "writing Workbooks" do + it "should create a new empty workbook" do + name = 'new-workbook.xlsx' + book = POI::Workbook.create(name) + book.should_not be_nil + end + + it "should create a new workbook and write something to it" do + name = TestDataFile.expand_path("timesheet-#{Time.now.strftime('%Y%m%d%H%M%S%s')}.xlsx") + create_timesheet_spreadsheet(name) + book = POI::Workbook.open(name) + book.worksheets.size.should == 1 + book.worksheets[0].name.should == 'Timesheet' + book.filename.should == name + book['Timesheet!A3'].should == 'Yegor Kozlov' + book.cell('Timesheet!J13').formula_value.should == 'SUM(J3:J12)' + FileUtils.rm_f name + end + + def create_timesheet_spreadsheet name='spec/data/timesheet.xlsx' + titles = ["Person", "ID", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Total\nHrs", "Overtime\nHrs", "Regular\nHrs"] + sample_data = [ + ["Yegor Kozlov", "YK", 5.0, 8.0, 10.0, 5.0, 5.0, 7.0, 6.0], + ["Gisella Bronzetti", "GB", 4.0, 3.0, 1.0, 3.5, nil, nil, 4.0] + ] + + book = POI::Workbook.create(name) + title_style = book.create_style :font_height_in_points => 18, :boldweight => :boldweight_bold, + :alignment => :align_center, :vertical_alignment => :vertical_center + header_style = book.create_style :font_height_in_points => 11, :color => :white, :fill_foreground_color => :grey_50_percent, + :fill_pattern => :solid_foreground, :alignment => :align_center, :vertical_alignment => :vertical_center + cell_style = book.create_style :alignment => :align_center, :border_bottom => :border_thin, :border_top => :border_thin, + :border_left => :border_thin, :border_right => :border_thin, :bottom_border_color => :black, + :right_border_color => :black, :left_border_color => :black, :top_border_color => :black + form1_style = book.create_style :data_format => '0.00', :fill_pattern => :solid_foreground, :fill_foreground_color => :grey_25_percent, + :alignment => :align_center, :vertical_alignment => :vertical_center + form2_style = book.create_style :data_format => '0.00', :fill_pattern => :solid_foreground, :fill_foreground_color => :grey_40_percent, + :alignment => :align_center, :vertical_alignment => :vertical_center + + sheet = book.create_sheet 'Timesheet' + print_setup = sheet.print_setup + print_setup.landscape = true + sheet.fit_to_page = true + sheet.horizontally_center = true + + title_row = sheet.rows[0] + title_row.height_in_points = 45 + title_cell = title_row.cells[0] + title_cell.value = 'Weekly Timesheet' + title_cell.style = title_style + sheet.add_merged_region org.apache.poi.ss.util.CellRangeAddress.valueOf("$A$1:$L$1") + + header_row = sheet[1] + header_row.height_in_points = 40 + titles.each_with_index do | title, index | + header_cell = header_row[index] + header_cell.value = title + header_cell.style = header_style + end + + row_num = 2 + 10.times do + row = sheet[row_num] + row_num += 1 + titles.each_with_index do | title, index | + cell = row[index] + if index == 9 + cell.formula = "SUM(C#{row_num}:I#{row_num})" + cell.style = form1_style + elsif index == 11 + cell.formula = "J#{row_num} - K#{row_num}" + cell.style = form1_style + else + cell.style = cell_style + end + end + end + + # row with totals below + sum_row = sheet[row_num] + row_num += 1 + sum_row.height_in_points = 35 + cell = sum_row[0] + cell.style = form1_style + cell = sum_row[1] + cell.style = form1_style + cell.value = 'Total Hrs:' + (2...12).each do | cell_index | + cell = sum_row[cell_index] + column = (?A.ord + cell_index).chr + cell.formula = "SUM(#{column}3:#{column}12)" + if cell_index > 9 + cell.style = form2_style + else + cell.style = form1_style + end + end + row_num += 1 + sum_row = sheet[row_num] + row_num += 1 + sum_row.height_in_points = 25 + cell = sum_row[0] + cell.value = 'Total Regular Hours' + cell.style = form1_style + cell = sum_row[1] + cell.formula = 'L13' + cell.style = form2_style + sum_row = sheet[row_num] + row_num += 1 + cell = sum_row[0] + cell.value = 'Total Overtime Hours' + cell.style = form1_style + cell = sum_row[1] + cell.formula = 'K13' + cell.style = form2_style + + # set sample data + sample_data.each_with_index do |each, row_index| + row = sheet[2 + row_index] + each.each_with_index do | data, cell_index | + data = sample_data[row_index][cell_index] + next unless data + if data.kind_of? String + row[cell_index].value = data #.to_java(:string) + else + row[cell_index].value = data #.to_java(:double) + end + end + end + + # finally set column widths, the width is measured in units of 1/256th of a character width + sheet.set_column_width 0, 30*256 # 30 characters wide + (2..9).to_a.each do | column | + sheet.set_column_width column, 6*256 # 6 characters wide + end + sheet.set_column_width 10, 10*256 # 10 characters wide + + book.save + File.exist?(name).should == true + end +end
kameeoze/jruby-poi
7fa2804f53bdc41a51ac17e48fd32ad5707d1e33
Not quite ready for ruby 1.9
diff --git a/.travis.yml b/.travis.yml index 506fdb3..ffa0161 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,3 @@ language: ruby rvm: - jruby-18mode - - jruby-19mode
kameeoze/jruby-poi
de6f2886eb00a90575c01993be5de9b238d34b97
Changing the version of gem
diff --git a/jruby-poi.gemspec b/jruby-poi.gemspec index f550bbf..0ff4624 100644 --- a/jruby-poi.gemspec +++ b/jruby-poi.gemspec @@ -1,87 +1,87 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{jruby-poi} - s.version = "0.8.2" + s.version = "0.9.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = [%q{Scott Deming}, %q{Jason Rogers}] s.date = %q{2012-07-23} s.description = %q{A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI.} s.email = [%q{[email protected]}, %q{[email protected]}] s.executables = [%q{autospec}, %q{htmldiff}, %q{ldiff}, %q{rdebug}, %q{rspec}] s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ ".travis.yml", "Gemfile", "Gemfile.lock", "LICENSE", "NOTICE", "README.markdown", "Rakefile", "VERSION", "bin/autospec", "bin/htmldiff", "bin/ldiff", "bin/rdebug", "bin/rspec", "jruby-poi.gemspec", "lib/ooxml-lib/dom4j-1.6.1.jar", "lib/ooxml-lib/geronimo-stax-api_1.0_spec-1.0.jar", "lib/ooxml-lib/xmlbeans-2.3.0.jar", "lib/poi-3.7-20101029.jar", "lib/poi-examples-3.7-20101029.jar", "lib/poi-ooxml-3.7-20101029.jar", "lib/poi-ooxml-schemas-3.7-20101029.jar", "lib/poi-scratchpad-3.7-20101029.jar", "lib/poi.rb", "lib/poi/workbook.rb", "lib/poi/workbook/area.rb", "lib/poi/workbook/cell.rb", "lib/poi/workbook/named_range.rb", "lib/poi/workbook/row.rb", "lib/poi/workbook/workbook.rb", "lib/poi/workbook/worksheet.rb", "spec/data/simple_with_picture.ods", "spec/data/simple_with_picture.xls", "spec/data/spreadsheet.ods", "spec/data/timesheet.xlsx", "spec/data/various_samples.xlsx", "spec/facade_spec.rb", "spec/io_spec.rb", "spec/spec_helper.rb", "spec/support/java/jrubypoi/MockOutputStream.java", "spec/support/java/support.jar", "spec/support/matchers/cell_matcher.rb", "spec/workbook_spec.rb", "spec/writing_spec.rb", "spec_debug.sh" ] s.homepage = %q{http://github.com/kameeoze/jruby-poi} s.licenses = [%q{Apache}] s.require_paths = [%q{lib}] s.rubygems_version = %q{1.8.9} s.summary = %q{Apache POI class library for jruby} if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, [">= 2.11.0"]) s.add_development_dependency(%q<jeweler>, [">= 1.8.4"]) else s.add_dependency(%q<rspec>, [">= 2.11.0"]) s.add_dependency(%q<jeweler>, [">= 1.8.4"]) end else s.add_dependency(%q<rspec>, [">= 2.11.0"]) s.add_dependency(%q<jeweler>, [">= 1.8.4"]) end end
kameeoze/jruby-poi
10d7ccbc2f16146e11db40ac6e057986209b51fe
Fix area, make the method call more clear to avoid confusion
diff --git a/lib/poi/workbook/area.rb b/lib/poi/workbook/area.rb index e2f9095..bb93e3f 100644 --- a/lib/poi/workbook/area.rb +++ b/lib/poi/workbook/area.rb @@ -1,81 +1,81 @@ module POI class Area def initialize reference @ref = reference end def in workbook if single_cell_reference? ref = area.all_referenced_cells.first - return [workbook.single_cell, ref] + return [workbook.single_cell(ref)] end begin by_column = {} # refs = area.all_referenced_cells # slices = refs.enum_slice(refs.length/15) # slices.collect do |cell_refs| # Thread.start do # cell_refs.each do |cell_ref| # first = workbook.worksheets[cell_ref.sheet_name].first_row # last = workbook.worksheets[cell_ref.sheet_name].last_row # next unless cell_ref.row >= first && cell_ref.row <= last # # # ref = POI::CELL_REF.new(c.format_as_string) # cell = workbook.single_cell cell_ref # (by_column[cell_ref.cell_ref_parts.collect.last] ||= []) << cell # end # end # end.each {|t| t.join} area.all_referenced_cells.each do |cell_ref| first = workbook.worksheets[cell_ref.sheet_name].first_row last = workbook.worksheets[cell_ref.sheet_name].last_row next unless cell_ref.row >= first && cell_ref.row <= last # ref = POI::CELL_REF.new(c.format_as_string) cell = workbook.single_cell cell_ref (by_column[cell_ref.cell_ref_parts.collect.last] ||= []) << cell end by_column.each do |key, cells| by_column[key] = cells.compact end if by_column.length == 1 by_column.values.flatten else by_column end rescue [] end end def single_cell_reference? area.single_cell? #@ref == getFirstCell.formatAsString rescue false end private def area @area ||= new_area_reference end def new_area_reference begin return POI::AREA_REF.new(@ref) rescue # not a valid reference, so proceed through to see if it's a column-based reference end sheet_parts = @ref.split('!') area_parts = sheet_parts.last.split(':') area_start = "#{sheet_parts.first}!#{area_parts.first}" area_end = area_parts.last begin POI::AREA_REF.getWholeColumn(area_start, area_end) rescue raise "could not determine area reference for #{@ref}: #{$!.message}" end end end end
kameeoze/jruby-poi
79645144510a7fa96d00332195eb6571eb27053b
Add Travis badge
diff --git a/README.markdown b/README.markdown index bd8af54..156916b 100644 --- a/README.markdown +++ b/README.markdown @@ -1,87 +1,89 @@ [jruby-poi](http://github.com/kameeoze/jruby-poi) ========= +[![Build Status](https://secure.travis-ci.org/kameeoze/jruby-poi.png)](http://travis-ci.org/kameeoze/jruby-poi) + This little gem provides an alternative interface to the Apache POI java library, for JRuby. For now the API is targeted at wrapping spreadsheets. We may expand this in the future. INSTALL ======= * gem install jruby-poi USAGE ===== It's pretty simple really, create a POI::Workbook and access its sheets, rows, and cells. You can read from the spreadsheet, save it (as the filename with which you created or as a new spreadsheet via Workbook#save_as). require 'poi' # given an Excel spreadsheet whose first sheet (Sheet 1) has this data: # A B C D E # 1 4 A 2010-01-04 # 2 3 B =DATE(YEAR($E$1), MONTH($E$1), A2) # 3 2 C =DATE(YEAR($E$1), MONTH($E$1), A3) # 4 1 D =DATE(YEAR($E$1), MONTH($E$1), A4) workbook = POI::Workbook.open('spreadsheet.xlsx') sheet = workbook.worksheets["Sheet 1"] rows = sheet.rows # get a cell's value -- returns the value as its proper type, evaluating formulas if need be rows[0][0].value # => 4.0 rows[0][1].value # => nil rows[0][2].value # => 'A' rows[0][3].value # => nil rows[0][4].value # => 2010-01-04 as a Date instance rows[1][4].value # => 2010-01-03 as a Date instance rows[2][4].value # => 2010-01-02 as a Date instance rows[3][4].value # => 2010-01-01 as a Date instance # you can access a cell in array style as well... these snippets are all equivalent workbook.sheets[0][2][2] # => 'C' workbook[0][2][2] # => 'C' workbook.sheets['Sheet 1'][2][2] # => 'C' workbook['Sheet 1'][2][2] # => 'C' # you can access a cell in 3D cell format too workbook['Sheet 1!A1'] # => 4.0 # you can even refer to ranges of cells workbook['Sheet 1!A1:A3'] # => [4.0, 3.0, 2.0] # if cells E1 - E4 were a named range, you could refer to those cells by its name # eg. if the cells were named "dates"... workbook['dates'] # => dates from E1 - E4 # to get the Cell instance, instead of its value, just use the Workbook#cell method workbook.cell('dates') # => cells that contain dates from E1 to E4 workbook['Sheet 1!A1:A3'] # => cells that contain 4.0, 3.0, and 2.0 There's a formatted version of this code [here](http://gist.github.com/557607), but Github doesn't allow embedding script tags in Markdown. Go figure! TODO ==== * fix reading ODS files -- we have a broken spec for this in io_spec.rb * add APIs for updating cells in a spreadsheet * create API for non-spreadsheet files Contributors ============ * [Scott Deming](http://github.com/sdeming) * [Jason Rogers](http://github.com/jacaetevha) Note on Patches/Pull Requests ============================= * Fork the project. * Make your feature addition or bug fix. * Add tests for it. This is important so I don't break it in a future version unintentionally. * Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull) * Send me a pull request. Copyright ========= Copyright (c) 2010 Scott Deming and others. See NOTICE and LICENSE for details.
kameeoze/jruby-poi
a5cdbc83b8ccbeb39de52e8c132c935b95ff66ec
Version bump to 0.9.0
diff --git a/VERSION b/VERSION index 53a48a1..899f24f 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.8.2 \ No newline at end of file +0.9.0 \ No newline at end of file
kameeoze/jruby-poi
e0063569d5b07251c4362a7e8fbebfbc03b16e4f
Run specs in 1.8 and 1.9 jruby modes.
diff --git a/.travis.yml b/.travis.yml index da1b1ae..506fdb3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,2 +1,4 @@ +language: ruby rvm: - - jruby + - jruby-18mode + - jruby-19mode
kameeoze/jruby-poi
bacd84576f598453c036b428afddd2a8af7b5957
Fixed spec, use correct path helper for data files.
diff --git a/spec/writing_spec.rb b/spec/writing_spec.rb index a31a593..d8fea48 100644 --- a/spec/writing_spec.rb +++ b/spec/writing_spec.rb @@ -1,146 +1,146 @@ require 'spec_helper' require 'date' require 'stringio' describe "writing Workbooks" do it "should create a new empty workbook" do name = 'new-workbook.xlsx' book = POI::Workbook.create(name) book.should_not be_nil end it "should create a new workbook and write something to it" do - name = "spec/data/timesheet-#{Time.now.strftime('%Y%m%d%H%M%S%s')}.xlsx" + name = TestDataFile.expand_path("timesheet-#{Time.now.strftime('%Y%m%d%H%M%S%s')}.xlsx") create_timesheet_spreadsheet(name) book = POI::Workbook.open(name) book.worksheets.size.should == 1 book.worksheets[0].name.should == 'Timesheet' book.filename.should == name book['Timesheet!A3'].should == 'Yegor Kozlov' book.cell('Timesheet!J13').formula_value.should == 'SUM(J3:J12)' FileUtils.rm_f name end def create_timesheet_spreadsheet name='spec/data/timesheet.xlsx' titles = ["Person", "ID", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Total\nHrs", "Overtime\nHrs", "Regular\nHrs"] sample_data = [ ["Yegor Kozlov", "YK", 5.0, 8.0, 10.0, 5.0, 5.0, 7.0, 6.0], ["Gisella Bronzetti", "GB", 4.0, 3.0, 1.0, 3.5, nil, nil, 4.0] ] book = POI::Workbook.create(name) title_style = book.create_style :font_height_in_points => 18, :boldweight => :boldweight_bold, :alignment => :align_center, :vertical_alignment => :vertical_center header_style = book.create_style :font_height_in_points => 11, :color => :white, :fill_foreground_color => :grey_50_percent, :fill_pattern => :solid_foreground, :alignment => :align_center, :vertical_alignment => :vertical_center cell_style = book.create_style :alignment => :align_center, :border_bottom => :border_thin, :border_top => :border_thin, :border_left => :border_thin, :border_right => :border_thin, :bottom_border_color => :black, :right_border_color => :black, :left_border_color => :black, :top_border_color => :black form1_style = book.create_style :data_format => '0.00', :fill_pattern => :solid_foreground, :fill_foreground_color => :grey_25_percent, :alignment => :align_center, :vertical_alignment => :vertical_center form2_style = book.create_style :data_format => '0.00', :fill_pattern => :solid_foreground, :fill_foreground_color => :grey_40_percent, :alignment => :align_center, :vertical_alignment => :vertical_center sheet = book.create_sheet 'Timesheet' print_setup = sheet.print_setup print_setup.landscape = true sheet.fit_to_page = true sheet.horizontally_center = true title_row = sheet.rows[0] title_row.height_in_points = 45 title_cell = title_row.cells[0] title_cell.value = 'Weekly Timesheet' title_cell.style = title_style sheet.add_merged_region org.apache.poi.ss.util.CellRangeAddress.valueOf("$A$1:$L$1") header_row = sheet[1] header_row.height_in_points = 40 titles.each_with_index do | title, index | header_cell = header_row[index] header_cell.value = title header_cell.style = header_style end row_num = 2 10.times do row = sheet[row_num] row_num += 1 titles.each_with_index do | title, index | cell = row[index] if index == 9 cell.formula = "SUM(C#{row_num}:I#{row_num})" cell.style = form1_style elsif index == 11 cell.formula = "J#{row_num} - K#{row_num}" cell.style = form1_style else cell.style = cell_style end end end # row with totals below sum_row = sheet[row_num] row_num += 1 sum_row.height_in_points = 35 cell = sum_row[0] cell.style = form1_style cell = sum_row[1] cell.style = form1_style cell.value = 'Total Hrs:' (2...12).each do | cell_index | cell = sum_row[cell_index] column = (?A + cell_index).chr cell.formula = "SUM(#{column}3:#{column}12)" if cell_index > 9 cell.style = form2_style else cell.style = form1_style end end row_num += 1 sum_row = sheet[row_num] row_num += 1 sum_row.height_in_points = 25 cell = sum_row[0] cell.value = 'Total Regular Hours' cell.style = form1_style cell = sum_row[1] cell.formula = 'L13' cell.style = form2_style sum_row = sheet[row_num] row_num += 1 cell = sum_row[0] cell.value = 'Total Overtime Hours' cell.style = form1_style cell = sum_row[1] cell.formula = 'K13' cell.style = form2_style # set sample data sample_data.each_with_index do |each, row_index| row = sheet[2 + row_index] each.each_with_index do | data, cell_index | data = sample_data[row_index][cell_index] next unless data if data.kind_of? String row[cell_index].value = data #.to_java(:string) else row[cell_index].value = data #.to_java(:double) end end end # finally set column widths, the width is measured in units of 1/256th of a character width sheet.set_column_width 0, 30*256 # 30 characters wide (2..9).to_a.each do | column | sheet.set_column_width column, 6*256 # 6 characters wide end sheet.set_column_width 10, 10*256 # 10 characters wide book.save File.exist?(name).should == true end end
kameeoze/jruby-poi
34bb3b13dd4a9628e9cb87288114360219518aa4
Regenerate gemspec for version 0.8.2
diff --git a/jruby-poi.gemspec b/jruby-poi.gemspec index 500f1e9..95daee6 100644 --- a/jruby-poi.gemspec +++ b/jruby-poi.gemspec @@ -1,98 +1,90 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{jruby-poi} - s.version = "0.8.1" + s.version = "0.8.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Scott Deming", "Jason Rogers"] s.date = %q{2011-05-22} s.description = %q{A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI.} s.email = ["[email protected]", "[email protected]"] s.executables = ["autospec", "htmldiff", "ldiff", "rdebug", "rspec"] s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ ".travis.yml", "Gemfile", "Gemfile.lock", "LICENSE", "NOTICE", "README.markdown", "Rakefile", "VERSION", "bin/autospec", "bin/htmldiff", "bin/ldiff", "bin/rdebug", "bin/rspec", "jruby-poi.gemspec", "lib/ooxml-lib/dom4j-1.6.1.jar", "lib/ooxml-lib/geronimo-stax-api_1.0_spec-1.0.jar", "lib/ooxml-lib/xmlbeans-2.3.0.jar", "lib/poi-3.7-20101029.jar", "lib/poi-examples-3.7-20101029.jar", "lib/poi-ooxml-3.7-20101029.jar", "lib/poi-ooxml-schemas-3.7-20101029.jar", "lib/poi-scratchpad-3.7-20101029.jar", "lib/poi.rb", "lib/poi/workbook.rb", "lib/poi/workbook/area.rb", "lib/poi/workbook/cell.rb", "lib/poi/workbook/named_range.rb", "lib/poi/workbook/row.rb", "lib/poi/workbook/workbook.rb", "lib/poi/workbook/worksheet.rb", "spec/data/simple_with_picture.ods", "spec/data/simple_with_picture.xls", "spec/data/spreadsheet.ods", "spec/data/timesheet.xlsx", "spec/data/various_samples.xlsx", "spec/facade_spec.rb", "spec/io_spec.rb", "spec/spec_helper.rb", "spec/support/java/jrubypoi/MockOutputStream.java", "spec/support/java/support.jar", "spec/support/matchers/cell_matcher.rb", "spec/workbook_spec.rb", "spec/writing_spec.rb", "spec_debug.sh" ] s.homepage = %q{http://github.com/kameeoze/jruby-poi} s.licenses = ["Apache"] s.require_paths = ["lib"] - s.rubygems_version = %q{1.6.2} + s.rubygems_version = %q{1.5.1} s.summary = %q{Apache POI class library for jruby} - s.test_files = [ - "spec/facade_spec.rb", - "spec/io_spec.rb", - "spec/spec_helper.rb", - "spec/support/matchers/cell_matcher.rb", - "spec/workbook_spec.rb", - "spec/writing_spec.rb" - ] if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, [">= 2.5.0"]) - s.add_development_dependency(%q<jeweler>, ["~> 1.5.2"]) + s.add_development_dependency(%q<jeweler>, [">= 1.6.0"]) s.add_development_dependency(%q<rcov>, [">= 0"]) else s.add_dependency(%q<rspec>, [">= 2.5.0"]) - s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) + s.add_dependency(%q<jeweler>, [">= 1.6.0"]) s.add_dependency(%q<rcov>, [">= 0"]) end else s.add_dependency(%q<rspec>, [">= 2.5.0"]) - s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) + s.add_dependency(%q<jeweler>, [">= 1.6.0"]) s.add_dependency(%q<rcov>, [">= 0"]) end end
kameeoze/jruby-poi
20d8bed1cb4fdc574b0346bb4eb00b8407e95675
Version bump to 0.8.2
diff --git a/VERSION b/VERSION index c18d72b..53a48a1 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.8.1 \ No newline at end of file +0.8.2 \ No newline at end of file
kameeoze/jruby-poi
4e35d49a6be50cc87a27aafa86d39f7f6b75243d
Upgrading jeweler
diff --git a/Gemfile b/Gemfile index 9540af9..47ec0ff 100644 --- a/Gemfile +++ b/Gemfile @@ -1,9 +1,9 @@ source "http://rubygems.org" # Add dependencies to develop your gem here. # Include everything needed to run rake, tests, features, etc. group :development do gem "rspec", ">= 2.5.0" - gem "jeweler", "~> 1.5.2" + gem "jeweler", ">= 1.6.0" gem "rcov", ">= 0" end diff --git a/Gemfile.lock b/Gemfile.lock index 32ceb9b..36f4e13 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,29 +1,29 @@ GEM remote: http://rubygems.org/ specs: diff-lcs (1.1.2) git (1.2.5) - jeweler (1.5.2) + jeweler (1.6.0) bundler (~> 1.0.0) git (>= 1.2.5) rake rake (0.9.0) rcov (0.9.9) rcov (0.9.9-java) rspec (2.6.0) rspec-core (~> 2.6.0) rspec-expectations (~> 2.6.0) rspec-mocks (~> 2.6.0) rspec-core (2.6.2) rspec-expectations (2.6.0) diff-lcs (~> 1.1.2) rspec-mocks (2.6.0) PLATFORMS java ruby DEPENDENCIES - jeweler (~> 1.5.2) + jeweler (>= 1.6.0) rcov rspec (>= 2.5.0)
kameeoze/jruby-poi
fd2c5ee482113844cee8e73f978542fffcb7d50d
Revert "Version bump to 0.9.0"
diff --git a/VERSION b/VERSION index 899f24f..c18d72b 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.9.0 \ No newline at end of file +0.8.1 \ No newline at end of file
kameeoze/jruby-poi
206713a58fe789b0ba30bb160ebc951ab2d8b6f0
Revert "Regenerate gemspec for version 0.9.0"
diff --git a/jruby-poi.gemspec b/jruby-poi.gemspec index a5773cb..500f1e9 100644 --- a/jruby-poi.gemspec +++ b/jruby-poi.gemspec @@ -1,98 +1,98 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{jruby-poi} - s.version = "0.9.0" + s.version = "0.8.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Scott Deming", "Jason Rogers"] s.date = %q{2011-05-22} s.description = %q{A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI.} s.email = ["[email protected]", "[email protected]"] s.executables = ["autospec", "htmldiff", "ldiff", "rdebug", "rspec"] s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ ".travis.yml", "Gemfile", "Gemfile.lock", "LICENSE", "NOTICE", "README.markdown", "Rakefile", "VERSION", "bin/autospec", "bin/htmldiff", "bin/ldiff", "bin/rdebug", "bin/rspec", "jruby-poi.gemspec", "lib/ooxml-lib/dom4j-1.6.1.jar", "lib/ooxml-lib/geronimo-stax-api_1.0_spec-1.0.jar", "lib/ooxml-lib/xmlbeans-2.3.0.jar", "lib/poi-3.7-20101029.jar", "lib/poi-examples-3.7-20101029.jar", "lib/poi-ooxml-3.7-20101029.jar", "lib/poi-ooxml-schemas-3.7-20101029.jar", "lib/poi-scratchpad-3.7-20101029.jar", "lib/poi.rb", "lib/poi/workbook.rb", "lib/poi/workbook/area.rb", "lib/poi/workbook/cell.rb", "lib/poi/workbook/named_range.rb", "lib/poi/workbook/row.rb", "lib/poi/workbook/workbook.rb", "lib/poi/workbook/worksheet.rb", "spec/data/simple_with_picture.ods", "spec/data/simple_with_picture.xls", "spec/data/spreadsheet.ods", "spec/data/timesheet.xlsx", "spec/data/various_samples.xlsx", "spec/facade_spec.rb", "spec/io_spec.rb", "spec/spec_helper.rb", "spec/support/java/jrubypoi/MockOutputStream.java", "spec/support/java/support.jar", "spec/support/matchers/cell_matcher.rb", "spec/workbook_spec.rb", "spec/writing_spec.rb", "spec_debug.sh" ] s.homepage = %q{http://github.com/kameeoze/jruby-poi} s.licenses = ["Apache"] s.require_paths = ["lib"] s.rubygems_version = %q{1.6.2} s.summary = %q{Apache POI class library for jruby} s.test_files = [ "spec/facade_spec.rb", "spec/io_spec.rb", "spec/spec_helper.rb", "spec/support/matchers/cell_matcher.rb", "spec/workbook_spec.rb", "spec/writing_spec.rb" ] if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, [">= 2.5.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_development_dependency(%q<rcov>, [">= 0"]) else s.add_dependency(%q<rspec>, [">= 2.5.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) end else s.add_dependency(%q<rspec>, [">= 2.5.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) end end
kameeoze/jruby-poi
46ab6e7e87a8322705a8720ca32cd980d7a491b4
Revert "Version bump to 0.0.0"
diff --git a/VERSION b/VERSION index bd52db8..899f24f 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.0.0 \ No newline at end of file +0.9.0 \ No newline at end of file
kameeoze/jruby-poi
7beb9d4ee007192e884a1319e1ce193820df0186
Version bump to 0.0.0
diff --git a/VERSION b/VERSION index 899f24f..bd52db8 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.9.0 \ No newline at end of file +0.0.0 \ No newline at end of file
kameeoze/jruby-poi
a1d36e5ee240a7beb96a601a28393e4b261f4beb
Regenerate gemspec for version 0.9.0
diff --git a/jruby-poi.gemspec b/jruby-poi.gemspec index 500f1e9..a5773cb 100644 --- a/jruby-poi.gemspec +++ b/jruby-poi.gemspec @@ -1,98 +1,98 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{jruby-poi} - s.version = "0.8.1" + s.version = "0.9.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Scott Deming", "Jason Rogers"] s.date = %q{2011-05-22} s.description = %q{A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI.} s.email = ["[email protected]", "[email protected]"] s.executables = ["autospec", "htmldiff", "ldiff", "rdebug", "rspec"] s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ ".travis.yml", "Gemfile", "Gemfile.lock", "LICENSE", "NOTICE", "README.markdown", "Rakefile", "VERSION", "bin/autospec", "bin/htmldiff", "bin/ldiff", "bin/rdebug", "bin/rspec", "jruby-poi.gemspec", "lib/ooxml-lib/dom4j-1.6.1.jar", "lib/ooxml-lib/geronimo-stax-api_1.0_spec-1.0.jar", "lib/ooxml-lib/xmlbeans-2.3.0.jar", "lib/poi-3.7-20101029.jar", "lib/poi-examples-3.7-20101029.jar", "lib/poi-ooxml-3.7-20101029.jar", "lib/poi-ooxml-schemas-3.7-20101029.jar", "lib/poi-scratchpad-3.7-20101029.jar", "lib/poi.rb", "lib/poi/workbook.rb", "lib/poi/workbook/area.rb", "lib/poi/workbook/cell.rb", "lib/poi/workbook/named_range.rb", "lib/poi/workbook/row.rb", "lib/poi/workbook/workbook.rb", "lib/poi/workbook/worksheet.rb", "spec/data/simple_with_picture.ods", "spec/data/simple_with_picture.xls", "spec/data/spreadsheet.ods", "spec/data/timesheet.xlsx", "spec/data/various_samples.xlsx", "spec/facade_spec.rb", "spec/io_spec.rb", "spec/spec_helper.rb", "spec/support/java/jrubypoi/MockOutputStream.java", "spec/support/java/support.jar", "spec/support/matchers/cell_matcher.rb", "spec/workbook_spec.rb", "spec/writing_spec.rb", "spec_debug.sh" ] s.homepage = %q{http://github.com/kameeoze/jruby-poi} s.licenses = ["Apache"] s.require_paths = ["lib"] s.rubygems_version = %q{1.6.2} s.summary = %q{Apache POI class library for jruby} s.test_files = [ "spec/facade_spec.rb", "spec/io_spec.rb", "spec/spec_helper.rb", "spec/support/matchers/cell_matcher.rb", "spec/workbook_spec.rb", "spec/writing_spec.rb" ] if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, [">= 2.5.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_development_dependency(%q<rcov>, [">= 0"]) else s.add_dependency(%q<rspec>, [">= 2.5.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) end else s.add_dependency(%q<rspec>, [">= 2.5.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) end end
kameeoze/jruby-poi
86dc3e048f4ee5532dfcc6ee3b138d68c79985cc
Version bump to 0.9.0
diff --git a/VERSION b/VERSION index c18d72b..899f24f 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.8.1 \ No newline at end of file +0.9.0 \ No newline at end of file
kameeoze/jruby-poi
8135f29988f5a0f406442644e7e712a9eff76967
Rakefile fix for gem release
diff --git a/Rakefile b/Rakefile index 23ac214..71fb620 100644 --- a/Rakefile +++ b/Rakefile @@ -1,34 +1,35 @@ require 'rubygems' require 'bundler' begin Bundler.setup(:default, :development) rescue Bundler::BundlerError => e $stderr.puts e.message $stderr.puts "Run `bundle install` to install missing gems" exit e.status_code end require 'rake' require 'jeweler' require 'rspec/core' require 'rspec/core/rake_task' # gemify Jeweler::Tasks.new do |gemspec| gemspec.name = "jruby-poi" gemspec.summary = "Apache POI class library for jruby" gemspec.description = "A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI." gemspec.license = "Apache" gemspec.email = ["[email protected]", "[email protected]"] gemspec.homepage = "http://github.com/kameeoze/jruby-poi" gemspec.authors = ["Scott Deming", "Jason Rogers"] end +Jeweler::RubygemsDotOrgTasks.new # test RSpec::Core::RakeTask.new(:spec) RSpec::Core::RakeTask.new(:rcov) do |spec| spec.rcov = true end task :default => :spec
kameeoze/jruby-poi
3689fe3809cec76dd6a7613c7c499141a7867a43
Regenerate gemspec for version 0.8.1
diff --git a/jruby-poi.gemspec b/jruby-poi.gemspec index 4578ebe..500f1e9 100644 --- a/jruby-poi.gemspec +++ b/jruby-poi.gemspec @@ -1,98 +1,98 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{jruby-poi} s.version = "0.8.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Scott Deming", "Jason Rogers"] s.date = %q{2011-05-22} s.description = %q{A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI.} s.email = ["[email protected]", "[email protected]"] s.executables = ["autospec", "htmldiff", "ldiff", "rdebug", "rspec"] s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ ".travis.yml", "Gemfile", "Gemfile.lock", "LICENSE", "NOTICE", "README.markdown", "Rakefile", "VERSION", "bin/autospec", "bin/htmldiff", "bin/ldiff", "bin/rdebug", "bin/rspec", "jruby-poi.gemspec", "lib/ooxml-lib/dom4j-1.6.1.jar", "lib/ooxml-lib/geronimo-stax-api_1.0_spec-1.0.jar", "lib/ooxml-lib/xmlbeans-2.3.0.jar", "lib/poi-3.7-20101029.jar", "lib/poi-examples-3.7-20101029.jar", "lib/poi-ooxml-3.7-20101029.jar", "lib/poi-ooxml-schemas-3.7-20101029.jar", "lib/poi-scratchpad-3.7-20101029.jar", "lib/poi.rb", "lib/poi/workbook.rb", "lib/poi/workbook/area.rb", "lib/poi/workbook/cell.rb", "lib/poi/workbook/named_range.rb", "lib/poi/workbook/row.rb", "lib/poi/workbook/workbook.rb", "lib/poi/workbook/worksheet.rb", "spec/data/simple_with_picture.ods", "spec/data/simple_with_picture.xls", "spec/data/spreadsheet.ods", "spec/data/timesheet.xlsx", "spec/data/various_samples.xlsx", "spec/facade_spec.rb", "spec/io_spec.rb", "spec/spec_helper.rb", "spec/support/java/jrubypoi/MockOutputStream.java", "spec/support/java/support.jar", "spec/support/matchers/cell_matcher.rb", "spec/workbook_spec.rb", "spec/writing_spec.rb", "spec_debug.sh" ] s.homepage = %q{http://github.com/kameeoze/jruby-poi} s.licenses = ["Apache"] s.require_paths = ["lib"] - s.rubygems_version = %q{1.5.1} + s.rubygems_version = %q{1.6.2} s.summary = %q{Apache POI class library for jruby} s.test_files = [ "spec/facade_spec.rb", "spec/io_spec.rb", "spec/spec_helper.rb", "spec/support/matchers/cell_matcher.rb", "spec/workbook_spec.rb", "spec/writing_spec.rb" ] if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, [">= 2.5.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_development_dependency(%q<rcov>, [">= 0"]) else s.add_dependency(%q<rspec>, [">= 2.5.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) end else s.add_dependency(%q<rspec>, [">= 2.5.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) end end
kameeoze/jruby-poi
e578fee5a0d4dc86cef0b0084514d957c8ef99e1
Regenerate gemspec for version 0.8.1
diff --git a/jruby-poi.gemspec b/jruby-poi.gemspec index e76e44e..4578ebe 100644 --- a/jruby-poi.gemspec +++ b/jruby-poi.gemspec @@ -1,97 +1,98 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{jruby-poi} - s.version = "0.8.0" + s.version = "0.8.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Scott Deming", "Jason Rogers"] s.date = %q{2011-05-22} s.description = %q{A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI.} s.email = ["[email protected]", "[email protected]"] s.executables = ["autospec", "htmldiff", "ldiff", "rdebug", "rspec"] s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ ".travis.yml", "Gemfile", "Gemfile.lock", "LICENSE", "NOTICE", "README.markdown", "Rakefile", "VERSION", "bin/autospec", "bin/htmldiff", "bin/ldiff", "bin/rdebug", "bin/rspec", "jruby-poi.gemspec", "lib/ooxml-lib/dom4j-1.6.1.jar", "lib/ooxml-lib/geronimo-stax-api_1.0_spec-1.0.jar", "lib/ooxml-lib/xmlbeans-2.3.0.jar", "lib/poi-3.7-20101029.jar", "lib/poi-examples-3.7-20101029.jar", "lib/poi-ooxml-3.7-20101029.jar", "lib/poi-ooxml-schemas-3.7-20101029.jar", "lib/poi-scratchpad-3.7-20101029.jar", "lib/poi.rb", "lib/poi/workbook.rb", "lib/poi/workbook/area.rb", "lib/poi/workbook/cell.rb", "lib/poi/workbook/named_range.rb", "lib/poi/workbook/row.rb", "lib/poi/workbook/workbook.rb", "lib/poi/workbook/worksheet.rb", "spec/data/simple_with_picture.ods", "spec/data/simple_with_picture.xls", "spec/data/spreadsheet.ods", "spec/data/timesheet.xlsx", "spec/data/various_samples.xlsx", "spec/facade_spec.rb", "spec/io_spec.rb", "spec/spec_helper.rb", "spec/support/java/jrubypoi/MockOutputStream.java", "spec/support/java/support.jar", "spec/support/matchers/cell_matcher.rb", "spec/workbook_spec.rb", "spec/writing_spec.rb", "spec_debug.sh" ] s.homepage = %q{http://github.com/kameeoze/jruby-poi} + s.licenses = ["Apache"] s.require_paths = ["lib"] s.rubygems_version = %q{1.5.1} s.summary = %q{Apache POI class library for jruby} s.test_files = [ "spec/facade_spec.rb", "spec/io_spec.rb", "spec/spec_helper.rb", "spec/support/matchers/cell_matcher.rb", "spec/workbook_spec.rb", "spec/writing_spec.rb" ] if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, [">= 2.5.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_development_dependency(%q<rcov>, [">= 0"]) else s.add_dependency(%q<rspec>, [">= 2.5.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) end else s.add_dependency(%q<rspec>, [">= 2.5.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) end end
kameeoze/jruby-poi
52974b5c545ee55743e1984aab83cdf3d9583a0b
Cleaning Rakefile
diff --git a/Rakefile b/Rakefile index 44c375b..23ac214 100644 --- a/Rakefile +++ b/Rakefile @@ -1,29 +1,34 @@ require 'rubygems' + require 'bundler' begin Bundler.setup(:default, :development) rescue Bundler::BundlerError => e $stderr.puts e.message $stderr.puts "Run `bundle install` to install missing gems" exit e.status_code end -require 'rake' - +require 'rake' require 'jeweler' +require 'rspec/core' +require 'rspec/core/rake_task' + +# gemify Jeweler::Tasks.new do |gemspec| gemspec.name = "jruby-poi" gemspec.summary = "Apache POI class library for jruby" gemspec.description = "A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI." gemspec.license = "Apache" gemspec.email = ["[email protected]", "[email protected]"] gemspec.homepage = "http://github.com/kameeoze/jruby-poi" gemspec.authors = ["Scott Deming", "Jason Rogers"] end -require 'rspec/core' -require 'rspec/core/rake_task' +# test RSpec::Core::RakeTask.new(:spec) RSpec::Core::RakeTask.new(:rcov) do |spec| spec.rcov = true end + +task :default => :spec