Wednesday, January 20, 2010

Recipe 17.2. Drawing Arcs, Ellipses, and Circles










Recipe 17.2. Drawing Arcs, Ellipses, and Circles



17.2.2. Problem


You


want to draw open or filled curves. For example, you want to draw a pie chart showing the results of a user poll.




17.2.3. Solution


To draw an arc, use
ImageArc( ):


ImageArc($image, $x, $y, $width, $height, $start, $end, $color);



To draw an ellipse, use ImageArc( ) and set $start to 0 and $end to 360:


ImageArc($image, $x, $y, $width, $height, 0, 360, $color);



To draw a circle, use ImageArc( ), set $start to 0, set $end to 360, and use the same value for both $width and $height:


ImageArc($image, $x, $y, $diameter, $diameter, 0, 360, $color);





17.2.4. Discussion


Because the ImageArc( ) function is highly flexible, you can easily create common curves such as ellipses and circles by passing it the right values. Like many GD functions, the first parameter is the canvas. The next two parameters are the x and y coordinates for the center position of the arc. After that comes the arc width and height. Since a circle is an arc with the same width and height, to draw a circle, set both numbers to the diameter of the circle.


The sixth and seventh parameters are the starting and ending angles, in degrees. A value of 0 is at three o'clock. The arc then moves clockwise, so 90 is at six o'clock, 180 is at nine o'clock, and 270 is at the top of the hour. (Be careful'this behavior is not consistent among all GD functions. For example, when you rotate text, you turn in a counterclockwise direction.) Since the arc's center is located at ($x,$y), if you draw a semicircle from 0 to 180, it doesn't start at ($x,$y); instead, it begins at ($x+($diameter/2),$y).


As usual, the last parameter is the arc color.


For example, this draws an open black circle with a diameter of 100 pixels centered on the canvas, as shown in the left half of Figure 17-3:


$image = ImageCreate(100,100);
$bg = ImageColorAllocate($image, 255, 255, 255);
$black = ImageColorAllocate($image, 0, 0, 0);
ImageArc($image, 50, 50, 100, 100, 0, 360, $black);



To produce a solid ellipse or circle, call
ImageFillToBorder( ):


ImageArc($image, $x, $y, $diameter, $diameter, 0, 360, $color);
ImageFillToBorder($image, $x, $y, $color, $color);



The ImageFillToBorder( ) function floods a region beginning at ($x,$y) with the color specified as the last parameter until it hits the edge of the canvas or runs into a line with the same color as the third parameter.


Incorporating this into the earlier example gives:


$image = ImageCreate(100,100);
$bg = ImageColorAllocate($image, 255, 255, 255);
$black = ImageColorAllocate($image, 0, 0, 0);
ImageArc($image, 50, 50, 100, 100, 0, 360, $black);
ImageFillToBorder($image, 50, 50, $black, $black);



The output is shown in the right half of Figure 17-3.



An open black circle and a filled black circle




If you're running GD 2.x, you can call ImageFilledArc( )
and pass in a final parameter that describes the fill style. GD 2.x also supports specific
ImageEllipse( ) and
ImageFilledEllipse( ) functions.




17.2.5. See Also


Recipe 17.2 for more on drawing other types of shapes; Recipe 17.3 for more on drawing with styles and brushes; documentation on ImageArc( ) at http://www.php.net/imagearc, ImageFilledArc( ) at http://www.php.net/imagefilledarc, and ImageFillToBorder( ) at http://www.php.net/imagefilltoborder.














The basic_ostream(ostream) Class








Class Name basic_ostream

Header File <ostream>

Classification Input/Output (Format Class)

Class Relationship Diagram



Class Description

Member Classes



basic_ios

sentry


Methods




explicit basic_ostream(basic_streambuf* Sb)

virtual ~basic_ostream()

basic_ostream& put(char_type CharValue)

basic_ostream& write(const char_type* Str, streamsize Num)

basic_ostream& flush()

pos_type tellp()

basic_ostream& seekp(pos_type Pos)

basic_ostream& seekp(off_type Pos, ios_base::seekdir Dir)





Class Description




The basic_ostream class implements the notion of the object oriented output stream. This
object oriented output stream can be a binary stream or a text stream. The object
oriented stream can be buffered, or unbuffered. The basic_ostream class has facilities
to process single characters, or blocks of characters. When characters or blocks of
characters are sent to an basic_ostream object the operation is referred to as insertion.
The cout and wcout objects are examples of basic_ostream objects that have been pre-defined.






Method basic_ostream()

Access Public

Classification Constructor

Syntax explicit basic_ostream(basic_streambuf* Sb)

Parameters Sb is the buffer object that will be used for the ostream
object.

Return None



Description



This basic_ostream() method is used to construct an object of type basic_ostream.







Method basic_ostream()

Access Public

Classification Constructor

Syntax virtual ~basic_ostream()

Parameters None

Return None



Description



This basic_ostream() method is used to destruct an object of type basic_ostream.







Method put()

Access Public

Classification Modifier

Syntax basic_ostream<charT,traits>& put(char_type CharValue)

Parameters CharValue is the character that is inserted into the
output stream

Return This method returns a reference to the current ostream object.



Description



The put() method is used to insert a character into the output stream.







Method write()

Access Public

Classification Modifier

Syntax basic_ostream<charT,traits>& write(const char_type* Str, streamsize Num)

Parameters Num characters are inserted into the output stream starting at the location
pointed to by Str.


Return This method returns a reference to the current ostream object.



Description



The write() method is used to insert a character into the output stream. The insertion
operation will continue until Num characters are inserted into the output stream or
until an error condition occurs. If the output operation fails an exception may
be thrown e.g.



ios_base::failure








Method flush()

Access Public

Classification Modifier

Syntax basic_ostream<charT,traits>& flush()

Parameters None

Return This method returns a reference to the current ostream object.



Description



The flush() method has the effect of calling sync.







Method tellp()

Access Public

Classification Accessor

Syntax pos_type tellp()

Parameters None

Return This method returns the current put position.



Description



The tellp() method returns the current position of put pointer in the output stream.







Method seekp()

Access Public

Classification Modifier

Syntax basic_ostream<charT,traits>& seekp(pos_type Pos)

Parameters Pos is the position in the output stream that the point pointer
will be moved to.

Return This method returns a reference to the current ostream object.



Description



The seekp() method performs an absolute seek Pos from the beginning of the output
stream.







Method seekp()

Access Public

Classification Modifier

Syntax basic_ostream<charT,traits>& seekp(off_type Pos, ios_base::seekdir Dir)

Parameters Pos is the position in the output stream that the point pointer
will be moved to relative Dir. Dir can have the following
values

ios_base::beg
ios_base::cur
ios_base::end

Return This method returns a reference to the current ostream object.



Description



The seekp() method performs an relative seek to Pos from the direction specified by
Dir.




The Class Relationship Diagram of basic_ostream






Section 7.4. printf( )










7.4. printf( )




I was inspired to write the first edition of this book by the numerous questions I received about why there was no printf( ) function in Java. Part of the goal of that edition was to explain to readers why they didn't actually need it. Thus, I was a little perturbed when Java 5 added printf( ). Personally, I still don't think Java needs printf( ), but it's here now, so let's talk about it.


The printf( ) method makes heavy use of Java 5's new varargs feature. That is, a single method definition can support any number of arguments. In this case, the signature is:



public PrintStream printf(String format, Object... args)



A typical invocation looks like this:



System.out.printf("There are %f centimeters in %f inches.", 2.54*inches, inches);



If you're an old C hack, this is like coming home. The first argument is a format string containing both literal text and tags beginning with percent signs (%). To form the output, each tag is replaced by the corresponding argument that follows the format string. If the format string is the zeroth argument, the first tag is replaced by the first argument, the second tag by the second argument, and so forth. If there are more tags than arguments, printf( ) tHRows a java.util.MissingFormatArgumentException. This is a subclass of IllegalFormatException, which is a runtime exception, so you don't have to catch it. If there are more arguments than tags, the extra arguments are silently ignored.


The letter(s) after the percent sign in the format tag specify how the number is interpreted. For instance, %f means that the number is formatted as a floating-point number with a decimal sign. %d formats the argument as a decimal integer. %x formats the number as a hexadecimal integer. %X also formats the number as a hexadecimal integer but uses the uppercase letters A-F instead of the lowercase letters a-f to represent 10-15.



Most of the time, changing a lowercase conversion specifier to uppercase changes the formatted string from lowercase to uppercase. However, there are a few exceptions to this rule.



There are a couple of dozen tags for different kinds of data. Not all data is compatible. For instance, if you use %x to format a double as a hexadecimal integer, printf( ) throws a java.util.IllegalFormatConversionException. Again, this is a runtime exception and a subclass of IllegalFormatException.


So far, this isn't anything that can't be done easily with println( ) and string concatenation. What makes printf( ) more convenient for some uses is that the tags can also contain width and precision specifiers. For example, suppose we wrote the previous statement like this instead:



System.out.printf("There are %.3f centimeters in %.2f feet.", 2.54*feet, feet);



%.3f means that the centimeters will be formatted as a decimal number with exactly three digits after the decimal point. %.2f means that the number will be rounded to only two decimal places. This gives more legible output, like "There are 21.691 centimeters in 8.54 feet" instead of "There are 21.690925 centimeters in 8.539734 feet."


A number before the decimal point in the format tag specifies the minimum width of the formatted string. For instance, %7.3f formats a decimal number exactly seven characters wide with exactly three digits after the decimal point. Those seven characters include the decimal point, so there will be exactly three digits to the left of the decimal point. If the number is smaller than 100, it will be padded on the left with spaces to make seven characters. Zeros will be added to the right of the decimal point if necessary to pad it to three decimal places.


Consider this Java 1.4 code fragment that prints a three-column table of the angles between 0 and 360 degrees in degrees, radians, and grads, using only println( ):



for (double degrees = 0.0; degrees < 360.0; degrees++) {
double radians = Math.PI * degrees / 180.0;
double grads = 400 * degrees / 360;
System.out.println(degrees + " " + radians + " " + grads);
}



Its output looks like this (not very pretty):



0.0 0.0 0.0
1.0 0.017453292519943295 1.1111111111111112
2.0 0.03490658503988659 2.2222222222222223
3.0 0.05235987755982988 3.3333333333333335
...



In Java 5, printf( ) can easily format each number exactly five characters wide with one digit after the decimal point:



for (double degrees = 0.0; degrees < 360.0; degrees++) {
double radians = Math.PI * degrees / 180.0;
double grads = 400 * degrees / 360;
System.out.printf("%5.1f %5.1f %5.1f\n", degrees , radians, grads);
}



Here's the start of the output:



0.0 0.0 0.0
1.0 0.0 1.1
2.0 0.0 2.2
3.0 0.1 3.3
...



Notice how nicely everything lines up in a monospaced font? This is incredibly useful for the two dozen programmers using Java to generate reports for VT-100 terminals and letter-quality printouts on green-and-white barred computer paper. (Those readers who haven't written any software like that since 1984, and certainly those readers who weren't even born in 1984, should now see why I'm less than thrilled with the addition of this 1970s technology to a 21st-century language.)


Of course, programmers printing text in proportional-width fonts, GUI table components, HTML reports, XML documents styled with XSL stylesheets, and any other output format produced since 1992 may be less enamored of this style of programming. Anyway, Java has it now. You don't have to use it (or read the rest of this chapter) if you don't need it.












Tuesday, January 19, 2010

Software Synthesis





Software
Synthesis



Thus far we have concentrated on music
creation using
MIDI and
external sound-creation devices such as synthesizers, but what if you want to
use your computer as a synthesizer? No problem!



What is a software synthesizer? Considering
what a synthesizer does, converting electricity into sound, it stands to reason
that a computer with a soundcard would also be able to convert electricity into
sound. The only hitch is that you need a fairly powerful computer to do this,
which is why MIDI is so nice�it doesn't require a 1-GHz system to achieve
amazing results. Of course, the trade-off is the expense of the synthesizers. However,
if you find yourself with an extra dozen CPU cycles lying around doing nothing,
give a software synthesizer a try. Here's a few from
style='color:#003399'>www.freshmeat.net that might
meet your needs:



style='font-size:10.0pt;font-family:Symbol'>�        
aRts: analog real-time synthesizer



style='font-size:10.0pt;font-family:Symbol'>�        
BacteriuM: virtual analog matrix synthesizer



style='font-size:10.0pt;font-family:Symbol'>�        
Cumulus: asynchronous grain synthesizer



lang=EN-GB style='font-size:10.0pt;font-family:Symbol'>�        
Freebirth: integrated bass synthesizer/step
sequencer/sample player



lang=EN-GB style='font-size:10.0pt;font-family:Symbol'>�        
gAlan: modular synthesizer�drum
machine�sequencer�effects unit for Linux



style='font-size:10.0pt;font-family:Symbol'>�        
SpiralSynth: a software synthesizer



So what do they do? Using your soundcard,
they shape bit patterns into sound. They model old-style analog synthesizers
that had lots of knobs, buttons, and switches and produced very rich sound. If
you like to tinker with stuff, you will probably like analog modeling
synthesizers, as they are known, because they allow you to fiddle with all
aspects of sound, from waveforms to filters and more.



The interesting thing about these tools is
that the sound you create can be stored to a file. So then what? Later in this
chapter you will learn how to use these stored sounds in two other types of
music creation applications for Linux.



 





Chapter 2. Client-side JavaScript








 

 












Chapter 2. Client-side JavaScript





Client-side JavaScript is the name given to JavaScript code that is

embedded within an HTML file and executed by a web browser. In

addition to the core objects described in the previous section,

client-side JavaScript code has access to a number of other objects

that represent the web browser, the document displayed in the

browser, and the contents of that document. Client-side JavaScript

programs are usually event-based, which means that JavaScript

event handlers are executed in response to user

interactions with the browser and the document. The client-side

JavaScript scripting framework is powerful enough to open substantial

security holes in web browsers. For this reason, web browsers

typically restrict the actions of client-side scripts. This section

starts by explaining how JavaScript code is embedded in HTML files,

then goes on to introduce the client-side JavaScript objects,

JavaScript events and event handling, and JavaScript security

restrictions.
















     

     


    Section A.4. #4 Tools for Creating Web Pages










    A.4. #4 Tools for Creating Web Pages


    Now that you know XHTML and CSS you're in a good position to decide if tools like Dreamweaver, GoLive, and FrontPage are for you. All these applications attempt to provide what-you-see-is-what-you-get (WYSIWYG) tools for creating Web pages. We're sure you know enough about XHTML and browser support to know that this goal, while worthwhile, also comes up short from time to time. But, that said, these tools also provide some very handy features, even if you're writing a lot of the XHTML yourself:


    • A "code" window for entering XHTML and CSS with syntax checking to catch common mistakes and suggest common names and attributes as you type.

    • A preview and publish functionality that allows you to test pages before making them "live" on the Web.

    • A site manager that allows you to organize your site, and also keeps your local changes in synch with your Web site on the server. Note that this usually takes care of all the FTP work for you.


    These tools are also not without their downsides:


    • Often these tools lag behind standards in terms of support, so to keep your XHTML and CSS current you'll need to write the XHTML yourself.

    • Often these tools don't enforce strict standards, and may allow you to get sloppy with your XHTML and CSS, so don't forget to validate (some tools help you validate as well).


    Keep in mind you can use a combination of simple editors along with these more sophisticated tools; one solution doesn't have to fit all your needs. So use a page creation tool when it makes sense.



    A.4.1. Some tools to consider:


    • Macromedia Dreamweaver

    • Adobe GoLive

    • Microsoft FrontPage

    • GNU Emacs (open source)













    Chapter 6. Tackling Large Projects



    [ Team LiB ]






    Chapter 6. Tackling Large Projects



    A Large System, Produced By Expanding The Dimensions of A Smaller System, Does Not Behave Like The Smaller System.

    �John Gall


    Large, multifile projects differ from smaller ones not only in the challenges you will encounter when examining their code but also in the opportunities they provide for understanding them. In this chapter we review some common techniques used in the implementation of large projects and then examine specific elements typically comprising the development process of such projects. We will describe how large projects are organized, their build and configuration process, how different file versions are controlled, the special role of project-specific tools, and typical testing strategies. For these elements we sketch characteristic setups you will encounter and provide some hints on how you can use them to enhance your navigation and comprehension capabilities.






      [ Team LiB ]