[ Prev | Index | Next ]
Japanese English
Now Loading...
Download
Please download on PC (not smartphone) and extract the ZIP file. Then double-click VCSSL.bat (batch file) to execute for Microsoft® Windows®, or execute VCSSL.jar (JAR file) on the command line for Linux® and other OSes.
For details, see How to Use.
You are free to use and modify this program and material, even for educational or commercial use. » Details

Sine Wave Animation

This VCSSL program draws an animated sine wave graph based on parameters like amplitude, wavelength, and period.

- Table of Contents -

Sponsored Link


How to Use

Download and Extract

At first, click the "Download" button at the above of the title of this page by your PC (not smartphone). A ZIP file will be downloaded.

If you are using Windows, right-click the ZIP file and choose "Properties" from the menu, and enable "Unblock" checkbox at the right-bottom (in the line of "Security") of the properties-window. Otherwise, when you extract the ZIP file or when you execute the software, security warning messages may pop up and the extraction/execution may fail.

Then, please extract the ZIP file. On general environment (Windows®, major Linux distributions, etc.), you can extract the ZIP file by selecting "Extract All" and so on from right-clicking menu.

» If the extraction of the downloaded ZIP file is stopped with security warning messages...

Execute this Program

Next, open the extracted folder and execute this VCSSL program.

For Windows

Double-click the following batch file to execute:

VCSSL__Double_Click_This_to_Execute.bat

For Linux, etc.

Execute "VCSSL.jar" on the command-line terminal as follows:

cd <extracted_folder>
java -jar VCSSL.jar

» If the error message about non-availability of "java" command is output...

Screen After Launch

When the program starts, you'll first be asked whether you'd like to manually input the wave parameters. If you don't need exact values (e.g., a precise wavelength), feel free to skip this by selecting "No."

After that, the graph window and the parameter control window will appear:

window

In the graph window, a sine wave will be shown as an animation. In the parameter window, you can adjust values like the wave's wavelength \(\lambda\), amplitude \(A\), and period \(T\) using sliders.

Closing the windows will end the program.

Concept Overview

Formula for a Sine Wave

There are many ways to write sine waves depending on the field or application, but when graphing them with the horizontal axis as \(x\), the vertical axis as \(y\), and time as \(t\), one common expression is:

\[ y = A \sin 2 \pi \bigg( \frac{t}{T} - \frac{x}{\lambda} \bigg) \]

To make the formula more general, you could include an initial phase term like \( + \delta \) inside the sine, but for simplicity, we'll assume it's zero for now (including it would just shift the sine wave's position at \(t = 0\).

In this formula:

  • \(A\) is the amplitude
  • \(\lambda\) is the wavelength
  • \(T\) is the period

Let's briefly look at what each of these parameters represents in a sine wave.

Amplitude \(A\)

The amplitude defines how far the wave swings up and down -- in other words, the "size" of the wave's oscillation.

Be careful, though: Amplitude refers to the distance from the center (which is \(y = 0\) in this case) to one end of the oscillation -- not the full height from top to bottom. That full height would be twice the amplitude.

The amplitude of the sine wave.

Wavelength\(\lambda\)

The wavelength controls the horizontal "shape" of the wave. The longer the wavelength, the more stretched the wave becomes along the x-axis. A shorter wavelength compresses the shape.

There are many ways to define wavelength, but one simple way to visualize it is:

The distance the wave must be shifted along the x-axis before its shape lines up exactly with itself again.

Or, more intuitively:

The distance it takes to go from a point, over one peak and one trough, and arrive at the next identical point (in phase).
The wavelength of the sine wave

Be careful not to confuse this with just the length of one peak or one trough -- that would only be half a wavelength! If you shift the wave by just a single peak, it won't align with itself. You need both a peak and a trough to complete one full cycle.

Period: \(T\)

The period is similar to the wavelength but in time rather than space. It describes how long it takes (in time) for one complete cycle to occur at a fixed position on the x-axis.

If you focus on a single point on the wave, the period is how long it takes for that point to return to the exact same state (same position and direction of motion).

Put more intuitively:

If you track a point that starts right at the peak of the wave (at a fixed \(x\), the time it takes to fall to the trough and rise back to the peak again is exactly one period.
The period of the sine wave

Starting at the peak is helpful because if you start at a random point, the wave may pass through the same vertical position twice in one cycle (once going up, once going down), which can be confusing. Focusing on the peak gives you one clean cycle per return.

Note: What if the wave doesn't align when shifted, or the motion is irregular?

Everything above applies nicely to ideal sine waves. But in reality, most natural waves or vibrations aren't perfect sine waves -- they may not align exactly when shifted, or their motion may be irregular.

So does that mean concepts like wavelength or period are only useful for ideal waves? Not at all!

Even complex, irregular waves can be broken down into a sum of many sine waves. That means you can analyze them in terms of how much of each wavelength or period is present in the mix.

For example:

  • A jagged, bumpy wave includes more short-wavelength sine components
  • A smooth, broad wave has mostly long-wavelength components
  • The same goes for short vs. long periods

In other words, real-world waves don't have just one wavelength or period -- they have a whole spectrum. Studying these distributions is critical in many scientific and engineering fields.

Code

This program is written in VCSSL. In this section, we'll walk through the code and explain its structure. VCSSL uses a simple C-style syntax, so if you're familiar with C or similar languages, the code should be easy to follow.

If you'd like to modify the graph range or experiment with customizing the code, open the "SineWave.vcssl" file in a text editor and make changes there. Since VCSSL is a scripting language, you don't need a separate compiler-just edit the file and run it directly.

Full Source Code

Let's take a look at the entire source code:

That's it. The program is a little over 200 lines long and quite compact. Each section of the code is explained via inline comments, but in the following sections, we'll walk through the logic in more detail from the top.

Header Section

Let's begin with the first four lines of the code:

The first line declares that the file uses UTF-8 character encoding. While this line isn't strictly necessary for the program to run, including it helps prevent character corruption when the script is executed on other operating systems.

The second line imports the Math library, which provides basic math functions. In this case, we use the sin function from this library to define the shape of the sine wave.

The third line imports the GUI library, which is used to build the settings window for controlling wave parameters.

The fourth line imports the Graph2D library, which provides functions to interact with the 2D graph software. Instead of rendering the sine wave manually, we'll pass coordinate data via arrays and let the graphing tool plot it for us.

Declaring the Wave Parameter Variables

Next, we declare variables for the three key parameters of the sine wave: amplitude, wavelength, and period.

As you can see, we use the variable names "amplitude", "wavelength", and "period". These values are updated when the user interacts with the sliders in the settings window.

Note: We could have named them exactly as they appear in the math formula-like A, \(\lambda\), and T-but this code is meant to evolve into a version that supports multiple sine waves (e.g., wave A, wave B, wave C). If we'd used single-letter variable names, we'd likely end up with confusing identifiers like A_A, T_B, etc. Also, using uppercase letters for regular variables can be misleading in contexts where uppercase is conventionally used for constants.

Variables Related to Graphing

Then, we define several variables used to control the graphing behavior.

Most of these variables are constants for setting the range of the graph and time-step values used in the animation loop -- the inline comments explain their purpose clearly.

The last two lines declare arrays that store the actual wave data to be plotted. The graphing software accepts arrays of coordinates and connects them with lines, effectively drawing the wave as a polyline made of small segments.

For a simpler example using arrays to plot on a graph, see: Plotting Arrays to a 2D Graph

Variables for the Settings Window

Next, we declare variables used for managing the components in the settings window. These are just placeholders for storing the IDs of each GUI component.

Each GUI component, such as a window or slider, gets assigned a unique ID number. These IDs are used to identify which component was interacted with-for example, when a specific slider is moved. For more details, see the GUI Development Guide.

Other Control Variables

Lastly, we declare a few more variables that handle the overall animation and control logic.
  • "speed" is adjusted by a slider in the settings window and determines how fast the wave animates.
  • "graph" stores the ID of the graph instance, similar to how component IDs are handled in the GUI. It’s used to reference the specific graph when updating its data or settings.
  • "continuesLoop" controls whether the animation should continue running. When set to false, the main loop exits and the program ends.
  • "t" is the time variable used in the sine wave formula. It increases gradually in each loop and resets when the "Reset Time" button is clicked.

That wraps up the global variable declarations!

Core Logic

Now let's look at the main logic of the program -- the overall flow of execution. It's all defined in the main function, which is executed automatically when the program starts.

The first thing this function does is call createGraphWindow() to launch the graph software, followed by createSettingWindow() to build the settings GUI. Both of these are user-defined functions written within the same code file and explained shortly after this.

Once those setup steps are done, the program enters the animation loop:

while ( continuesLoop ) {
      ...
}

Since "continuesLoop" remains true unless explicitly changed, this loop effectively runs infinitely -- until the user closes one of the windows.

Inside the loop, the program continuously updates the value of time "t", recalculates the wave shape by filling "waveX" and "waveY" arrays, and sends those arrays to the graph. This repeated update creates an animation effect -- just like a flipbook.

Let's zoom in on the part where the sine wave's coordinates are computed and sent to the graph:

For each "x" position (from X_MIN to X_MAX in steps of DX), the program calculates the corresponding wave height "y" using this line:

waveY[ i ] = amplitude * sin( 2.0 * PI * ( t/period - x/wavelength ) );

This directly implements the sine wave formula we saw earlier:

\[ y = A \sin 2 \pi \bigg( \frac{t}{T} - \frac{x}{\lambda} \bigg) \]

If you want to visualize a wave other than a basic sine wave, this is the line to modify.
(In the next article, for example, we'll simulate interference patterns using multiple sine waves.)

After plotting the wave on the graph, the program waits for 30 milliseconds (to control the animation speed), then repeats the process with a slightly updated time value.

When the user closes the window, the variable "continuesLoop" is set to false, causing the program to exit the loop and execute exit(), gracefully ending the session.

This might seem a bit roundabout -- why not just call exit() directly when the window is closed? That's a fair question. But if we did that, the event handler would terminate the program from a different thread while the main loop is still running. To keep things clean and orderly, we let the main loop detect the termination condition and exit on its own. It's not essential, just good practice.

That's the big picture of how the main routine works. What follows are smaller, more modular functions used to support it.

Manually Entering Wave Parameters - inputParameters() Function

At the very top of the main function, we call inputParameters() to ask the user whether they want to input wave values manually. If they choose "yes," the function uses the input() function to accept values and assigns them to global variables.

Although the wave parameters can be adjusted later using sliders, manual entry is sometimes more precise. For example, if the user wants to set the wavelength to an exact value, this method allows it.

We could also allow number inputs beside the sliders in the GUI window, but that would make the GUI more complex and harder to maintain -- so we opted for this simple input dialog instead. It's a practical tradeoff to keep the code concise.

Launching the Graph - createGraphWindow() Function

Also called at the start of main(), this function launches the 2D graph software and sets its initial configuration:

Everything is already commented in the code, but one important detail is that the graph ID returned by newGraph2D() is stored in the global variable "graph". This ID is used throughout the rest of the program whenever we send data or configure options for that particular graph instance.

Building the Settings Window - createSettingWindow Function

As seen at the beginning of the main function, the createSettingWindow() function builds the parameter control panel using sliders.

This function basically creates a window and mounts GUI components such as sliders and labels one by one. Some components have their IDs stored in global variables for reference, similar to how the graph ID is handled.

Since this is a standalone sample, the positions and labels are hardcoded. For details on each function and arguments, please refer to the GUI Development Guide.

Updating the Label Displaying Slider Values - updateInfoLabel Function

The updateInfoLabel() function, called in createSettingWindow, updates the label that shows the wave parameters as something like \((A=1.0, \lambda=2.0, T=0.5)\).

Since the parameter values are double-precision floating-point numbers, they can have long decimals. To make the display easier to read, this function rounds them to two decimal places using the round function.

Event Handlers

Finally, here are the event handler functions, which are called when GUI components like sliders or windows are interacted with.

When a slider is moved, this function updates the corresponding global variable. It also calls updateInfoLabel() to refresh the display with the current values.

This handles the time reset button. It resets the time variable t back to 0 when clicked.

These functions are triggered when the user closes either the settings window or the graph window. They set "continuesLoop = false", which exits the animation loop and ends the program.

License

The license of this VCSSL / Vnano code (the file with the extension ".vcssl" / ".vnano") is CC0 (Public Domain), so you can customize / divert / redistribute this VCSSL code freely.

Also, if example code written in C/C++/Java are displayed/distributed on Code section of this page, they also are distributed under CC0, unless otherwise noted.



Sponsored Link



Japanese English
[ Prev | Index | Next ]
Wave Interference Animation (Two Sine Waves on a Line)

Interactive simulation of wave interference between two 1D sine waves.
Circular Wave Animation

Draws the circular wave as 3D animation, under the specified wave parameters.
Sine Wave Animation

Interactive simulator for animating sine waves with adjustable parameters.
Vnano | Solve The Lorenz Equations Numerically

Solve the Lorenz equations, and output data to plot the solution curve (well-known as the "Lorenz Attractor") on a 3D graph.
Index
[ Prev | Index | Next ]
Wave Interference Animation (Two Sine Waves on a Line)

Interactive simulation of wave interference between two 1D sine waves.
Circular Wave Animation

Draws the circular wave as 3D animation, under the specified wave parameters.
Sine Wave Animation

Interactive simulator for animating sine waves with adjustable parameters.
Vnano | Solve The Lorenz Equations Numerically

Solve the Lorenz equations, and output data to plot the solution curve (well-known as the "Lorenz Attractor") on a 3D graph.
News From RINEARN
* VCSSL is developed by RINEARN.

Released: Latest Version of VCSSL with Fixes for Behavioral Changes on Java 24
2025-04-22 - VCSSL 3.4.50 released with a fix for a subtle behavioral change in absolute path resolution on network drives, introduced in Java 24. Details inside.

Released the Latest Versions of RINEARN Graph and VCSSL - Now Supporting Customizable Tick Positions and Labels!
2024-11-24 - Starting with this update, a new "MANUAL" tick mode is now supported, allowing users to freely specify the positions and labels of ticks on the graph. We'll explain the details and how to use it.

Released Exevalator 2.2: Now Compatible with TypeScript and Usable in Web Browsers
2024-10-22 - The open-source expression evaluation library, Exevalator, has been updated to version 2.2. It now supports TypeScript and can be used for evaluating expressions directly in web browsers. Explains the details.

Behind the Scenes of Creating an Assistant AI (Part 1: Fundamental Knowledge)
2024-10-07 - The first part of a series on how to create an Assistant AI. In this article, we introduce the essential knowledge you need to grasp before building an Assistant AI. What exactly is an LLM-based AI? What is RAG? And more.

Launching an Assistant AI to Support Software Usage!
2024-09-20 - We've launched an Assistant AI that answers questions about how to use RINEARN software and helps with certain tasks. Anyone with a ChatGPT account can use it for free. We'll explain how to use it.

Software Updates: Command Expansion in RINEARN Graph, and English Support in VCSSL
2024-02-05 - We updated our apps. This updates include "Enhancing the Command-Line Features of RINEARN Graph" and "Adding English Support to VCSSL." Dives into each of them!

Inside the Repetitive Execution Speedup Impremented in Vnano Ver.1.1
2024-01-17 - Delves into the update in Vnano 1.1 from a developer's viewpoint, providing detailed insights into the specific improvements made to the internal structure of the script engine.

Scripting Engine Vnano Ver.1.1 Released: Dramatic Speed Improvement for Repetitive Executions of the Same Content
2023-12-22 - Released the Vnano script engine Ver.1.1. In this version, we've made significant enhancements in processing speed by reducing the overhead of handling requests. Explains the details.