Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Lighting

The final effect that we are going to look at is called Lighting. As its name suggests, it allows you to specify how a node or a group should be lit. Three different types of lighting can be used, all of which are represented by classes in the javafx.scene.effect.light package. The Lighting class itself, like all the other effects, is in the javafx.scene.effect package.

To define the lighting for a node or group, you create an instance of the Lighting class and install it in the effect variable of that node or group. Using lighting will make your scenes look more three-dimensional than they otherwise would, as you'll see in the examples in this section. The variables of the Lighting class are listed in Table 20-18.

Table 20-18. Variables of the Lighting Class

Variable

Type

Access

Default

Description

light

Light

RW

DistantLight

The type of light to be used.

bumpInput

Effect

RW

null

The bump map to be applied.

contentInput

Effect

RW

null

The input to this effect, which is the target node itself if this value is null.

diffuseConstant

Number

RW

1.0

Determines how much diffuse light is reflected from the surface, in the range 0 to 2, inclusive.

specularConstant

Number

RW

0.3

Determines how much specular light is reflected from the surface, in the range 0 to 2, inclusive.

specularExponent

Number

RW

20

Determines how shiny the surface appears to be in the range 0 to 40, inclusive.

surfaceScale

Number

RW

1.5

Determines the height assigned to pixels in the source, based on their opacity. Valid range is 0 to 10, inclusive.

The light variable determines the type of lighting required, which must be one of DistantLight (which is the default), PointLight, and SpotLight. The other variables set the characteristics of the surface that will be lit and will be explained in the rest of this section by reference to examples.

The surfaceScale Variable

To create a 3D effect when lighting a 2D surface, the opacity value of each pixel is used as a guide to how "high" that pixel should appear to be when lit. Transparent pixels appear to be the lowest, while fully opaque pixels appear to be raised up from the surface. This effect can be increased or decreased by using the surfaceScale variable. Values that are greater than 1 cause the effect to be increased, while values between 0 and 1 cause it to be decreased. The same effect can also be seen at the edges of shapes.

The following code, which comes from the file javafxeffects/SurfaceScale.fx, shines a distant light on a rectangle. The details of the lighting are not important right now, but you'll see that the surfaceScale variable is bound to a slider. If you run this example, you can see the effect of varying the surfaceScale variable over its full range:

Rectangle {
    x: 20
    y: 20
    width: 100
    height: 100
    fill: Color.YELLOW
    effect: Lighting {
        light: DistantLight {
            azimuth: 0
            elevation: 30
        }
        surfaceScale: bind (scaleSlider.value as Number) / 10
    }
}

You can see how the surfaceScale value is used by comparing the two screenshots shown in Figure 20-32.

Figure 20-32

Figure 20-32 The surfaceScale variable of the Lighting effect

On the left of the figure, the surfaceScale value is 0, so there is no 3D effect at all. On the right, surfaceScale has its maximum possible value, and now you can see that the center of the rectangle appears to be raised up above its edges. The higher the surfaceScale value, the higher the center will appear to be.

The Bump Map

You can add additional surface relief by creating a bump map and installing it in the bumpInput variable of the Lighting effect. If this variable is null, the node on which the effect is applied is itself used to generate a bump map, which is what causes the 3D effect at the edges that you saw in Figure 20-32.

The bump map is just an Effect, which supplies pixels from which the relief of the lit surface is calculated. As before, the apparent height of a pixel on the lit shape depends on the opacity of the corresponding pixel of the bump map. This effect is affected by the value of the surfaceScale variable, as described in the preceding section.

A common way to specify a bump map is to create an image, set the opacity to reflect the contours that you want to appear in the finished result, and then turn it into an effect by using the Identity class that we discussed earlier in this chapter. The code in the file javafxeffects/BumpMap.fx shows how to apply a bump map in the form of an image file:

1      var logo = Image { url: "{__DIR__}javafxlogo.gif" };
2      Stage {
3          title: "Bump Map"
4          scene: Scene {
5              width: 240
6              height: 140
7              fill: Color.BLACK
8              content: [
9                  Rectangle {
10                     x: 20
11                     y: 20
12                     width: 200
13                     height: 100
14                     fill: Color.YELLOW
15                     effect: Lighting {
16                         light: DistantLight {
17                             azimuth: 90
18                             elevation: 25
19                         }
20                         bumpInput: Identity {
21                             source: logo
22                             x: 30
23                             y: 40
24                         }
25                     }
26                 }
27             ]
28         }
29     }

The code on line 1 loads the bump image from a file called logo.gif that is in the same directory as the script file. This image is then converted to an Effect by the code on lines 20 to 24, and placed appropriately relative to the rectangle node to which the lighting effect is applied by using the x and y variables of the Identity class. The lighting itself is a DistantLight, to which the image is supplied as the bump map on line 20.

The image that is used as the bump map is shown on the left of Figure 20-33. The image consists of the word JavaFX in black text on a white background. The white background is actually completely transparent, while the black text is completely opaque. You can see the effect of the bump map on the right of Figure 20-33, where the lighting effect causes the word JavaFX to appear to be raised above the surface of the Rectangle.

Figure 20-33

Figure 20-33 Using a bump map with a Lighting effect

You can apply the same effect to any node, including an ImageView, where you can use it to create the appearance of a watermark within the image.

DistantLight

The DistantLight class is used when you want to apply a more-or-less uniform light to a node or group. Depending on where the light source is, you may see some shadows, but you will not see reflections of the type that are a characteristic of PointLight and Spotlight, which are discussed in the sections that follow. DistantLight, PointLight, and Spotlight are all derived from the base class javafx.scene.effect.light.Light, which has a single variable called color (of type Color) that specifies the color of the light to be used, which is white by default. The other variables of the DistantLight class specify the position of the light source and are listed in Table 20-19.

Table 20-19. Variables of the DistantLight Class

Variable

Type

Access

Default

Description

azimuth

Number

RW

45

The azimuth of the light source, in degrees

elevation

Number

RW

45

The elevation of the light source, in degrees

The azimuth is the position of the light source on the plane of the scene. An azimuth angle of 0 degrees places the light source at the 3 o'clock position, one of 90 degrees moves it to 6 o'clock, and so on. Negative angles can also be used and are measured counterclockwise. For example, setting the azimuth variable to either -90 or 270 places the light source at 12 o'clock.

The elevation gives the angle of the light source above or below the plane of the scene. When the elevation is 0 or 180, the light source is on the plane of the scene, when it is 90, it is overhead the scene and shining directly down on it, and when it is 270 (or -90), it is directly below the scene.

The following code, which you will find in the file javafxeffects/DistantLight1.fx, allows you to move a DistantLight source around a large yellow circle to see the effect that is created:

Circle {
    centerX: 200
    centerY: 180
    radius: 150
    fill: Color.YELLOW
    effect: Lighting {
        light: DistantLight {
            azimuth: bind azimuthSlider.value
            elevation: bind elevationSlider.value
        }
        surfaceScale: 5
    }
}

Figure 20-34 shows two different configurations of the DistantLight source.

Figure 20-34

Figure 20-34 Using a DistantLight source

On the left of the figure, the azimuth and elevation variables both have the value 45, which places the light source at approximately the 4.30 position and elevated 45 degrees above its surface. You can see that this is the case because the lower-right edge of the circle is much brighter than the rest of it. On the right, the light source has been moved to the 9 o'clock position by setting the azimuth variable to 180 and moved very close to the plane of the scene as a result of the elevation, which is very nearly 0 degrees. Because of the low elevation, most of the circle is quite dark, with the exception of the edge at around the 9 o'clock position, which is closest to the light source.

It is worth examining here the effect of the diffuseConstant of the Lighting class. This constant acts as a multiplier to the RGB values of all the pixels on the lit surface. Therefore, you can use this variable to make the surface lighter or darker. The example in the file javafxeffects/DistantLight2.fx illustrates this by setting the diffuseConstant value of the Lighting effect to 1.5, which has the result of making the circle brighter, as you can see by comparing the result shown in Figure 20-35 with Figure 20-34, where this variable had the value 1.

Figure 20-35

Figure 20-35 The effect of the diffuseConstant on a lit surface

PointLight

PointLight represents a single point of light that is positioned somewhere relative to the surface to be lit. The variables of the PointLight class, as shown in Table 20-20, allow you to specify exactly where the light source should be placed.

Table 20-20. Variables of the PointLight Class

Variable

Type

Access

Default

Description

x

Number

RW

0

The x coordinate of the light source

y

Number

RW

0

The y coordinate of the light source

z

Number

RW

0

The z coordinate of the light source

In the following code, a PointLight source whose position is bound to the values of three sliders is created and applied to a large yellow circle. If you run this example, which can be found in the file javafxeffects/PointLight1.fx, you can experiment with the effect of changing the location of the light source:

Circle {
    centerX: 200
    centerY: 180
    radius: 150
    fill: Color.YELLOW
    effect: Lighting {
        light: PointLight {
            x: bind xSlider.value
            y: bind ySlider.value
            z: bind zSlider.value
        }
        surfaceScale: 5
        specularConstant: bind (specCSlider.value as Number) / 10
        specularExponent: bind specESlider.value
    }
}

You can see two different PointLight configurations in Figure 20-36. On the left, the light is at (x = 45, y = 45, z = 45), which is to the top left of the circle itself. You can see that a PointLight source results in a more concentrated area of illumination than a DistantLight. On the right of the figure, the light source has been moved so that its reflection has moved more toward the center of the circle.

Figure 20-36

Figure 20-36 Using a PointLight source

The size and intensity of the reflection depends on values of the specularConstant and specularExponent variables of the PointLight class. Like diffuseConstant, specularConstant is a multiplier that is applied to the RGB values of the lit source, so values greater than 1 make the reflection bright, while values less than 1 make it dimmer. The specularExponent controls the spread of the light and therefore the radius of the reflected area. Increasing values of specularExponent reduce this radius and therefore make the reflection brighter. You can see examples that use different settings for these variables in Figure 20-37.

Figure 20-37

Figure 20-37 The effects of the specularConstant and specularExponent variables

SpotLight

PointLight represents a single-point source of light that shines uniformly in every direction, much like the sun. SpotLight is a subclass of PointLight that acts like a point light source that radiates light over a more confined area. The rays of light are confined to the inside of a cone with its tip at the source. The axis of the cone points to a specified location on the surface of the object being lit. The combination of the position of the light source, the point at which it is aimed, and the width of the cone at the point at which the light reaches the lit object determines the lighting effect that you see. You can specify these values using the variables listed in Table 20-21.

Table 20-21. The Variables of the SpotLight Class

Variable

Type

Access

Default

Description

pointsAtX

Number

RW

0.0

The x coordinate of the point at which the light is aimed

pointsAtY

Number

RW

0.0

The y coordinate of the point at which the light is aimed

pointsAtZ

Number

RW

0.0

The z coordinate of the point at which the light is aimed

specularExponent

Number

RW

1.0

Controls the width of the light cone, in the range 0 to 4, inclusive

The following code, which is from the file javafxeffects/SpotLight1.fx, applies a SpotLight effect to the same circle that we illuminated with a PointLight source in the previous example. The light source is placed 60 pixels above the center of the circle, while the point at which it is aimed can be controlled by three sliders. The effect produced by the SpotLight with these initial variable settings is shown on the left of Figure 20-38.

Circle {
    centerX: 200
    centerY: 180
    radius: 150
    fill: Color.YELLOW
    effect: Lighting {
        light: SpotLight {
            pointsAtX: bind xSlider.value
            pointsAtY: bind ySlider.value
            pointsAtZ: bind zSlider.value
            x: 200
            y: 180
            z: 60
            specularExponent: bind (specESlider.value as Number)/10
        }
        surfaceScale: 5
    }
}
Figure 20-38

Figure 20-38 The SpotLight effect

Moving the aiming point changes the resultant lighting effect. When the light source is quite close to the target object, as it is in this case, even a small change in the aiming point can make a noticeable difference to the result. On the right of Figure 20-38, the aiming point has been moved only a small amount to the right and, as you can see, almost half of the circle is now in darkness.

The bottom slider in Figure 20-38 allows you to see the effect of changing the specularExponent value, 8 which is initially set to its default value of 1. Increasing this value makes the light cone narrower that produces a more focused beam and therefore a smaller and brighter effect on the target, as you can see in Figure 20-39, where this variable has its maximum value of 4.0. With this setting, almost all the light is confined to a small area around the aiming point.

Figure 20-39

Figure 20-39 The effect of the specularExponent variable of the SpotLight class

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020