Blending Borders Using Transparent Shader Material in Three.js

As a newcomer to the world of webgl, I have been learning about shaders and recently tried to create a smooth, transparent cloud. While I was successful in achieving this, there seems to be an issue with overlapping edges looking jagged in the images provided below.

I would appreciate it if someone could explain why this is happening and provide guidance on how to resolve it?

Thank you,

v77

Snippet

var camera, controls, scene, renderer;
var sceneCss, rendererCss;
var dirLight, ambientLight, pointLight;
var displacementMaterial;

var wH = window.innerHeight;
var wW = window.innerWidth;
var start = Date.now();
var properties;
var cloudRadius = 150;
var cloudMesh;

var noiseMaterial, noiseMap;
var uniforms, displamentUniforms;


$(document).ready(function() {
  //init Core Engine;
  init();
  //init All Engines; 
  onLoaded();
  animateAll();
});

//Give it life;
function init() {

  properties = {
    smoke: 2.0,
    heat: 0.0007,
    shapeBiasX: 1.5,
    shapeBiasY: 2.5,
    displacementScale: 40,
    displacementBias: -22,
    turbulence: 40,
    twist: 0,
    wireframes: false,
    rotationX: .5,
    rotationY: 0,
    rotationZ: 0,
    opacity: 1.0
  }

  // add camera and controls
  camera = new THREE.PerspectiveCamera(70, wW / wH, 0.1, 20000);
  camera.position.set(0, 0, 400);

  //PostProcess Materials
  sceneRenderTarget = new THREE.Scene();

  cameraOrtho = new THREE.OrthographicCamera(wW / -2, wW / 2, wH / 2, wH / -2, -10000, 10000);
  cameraOrtho.position.z = 100;
  cameraOrtho.updateProjectionMatrix();

  var plane = new THREE.PlaneGeometry(wW, wH);
  quadTarget = new THREE.Mesh(plane, new THREE.MeshBasicMaterial({ transparent: true, opacity: .1, color: 0x000000 }));
  quadTarget.position.z = -500;
  sceneRenderTarget.add(quadTarget);

  //
  //scene
  scene = new THREE.Scene();
  sceneCss = new THREE.Scene();
  fog = new THREE.FogExp2(0x212121, 0.002);
  scene.fog = fog;

  //renderer
  renderer = new THREE.WebGLRenderer({
    antialias: true
  });
  renderer.setSize(wW, wH);
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.sortObjects = false;
  renderer.domElement.style.zIndex = 0;
  renderer.setClearColor(0x222222);
  document.body.appendChild(renderer.domElement);
}

function onLoaded() {
  //Will Check Processes
  createClouds();
}

function createClouds() {

  uniforms = {
    time: {
      type: "f",
      value: 1.0
    },
    uSpeed: {
      type: "f",
      value: 1.0
    },
    scale: {
      type: "v2",
      value: new THREE.Vector2(1, 1)
    },
    opacity: {
      type: "f",
      value: 1.0
    }
  };

  noiseMaterial = new THREE.ShaderMaterial({
    uniforms: uniforms,
    vertexShader: document.getElementById('noise_vertex').textContent,
    fragmentShader: document.getElementById('noise_fragment').textContent,
    lights: false,
    wireframe: properties.wireframes
  });

  noiseMap = new THREE.WebGLRenderTarget(512, 512, {
    minFilter: THREE.LinearFilter,
    magFilter: THREE.LinearFilter,
    format: THREE.RGBFormat,
    wrapS: THREE.RepeatWrapping
  });

  displacementUniforms = {
    time: {
      type: "f",
      value: 1.0
    },

canvas {
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: -10
}

body {
  overflow: hidden;
  padding: 0;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r77/three.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.2.js"></script>
<script data-src="shaders/displacement_vertex.js" data-name="Displacement" type="x-shader/x-vertex" id="displacement_vertex">

...

Answer №1

Dealing with overlapping transparent materials in three.js can be tricky, but one way to minimize unwanted artifacts is by adjusting the material properties:

material.depthTest = false;

Of course, the effectiveness of this solution depends on your specific scenario.

It's important to note that this approach may not be effective if you also have opaque objects blocking the view of the transparent ones. Luckily, in this case, it doesn't seem to be a concern for you.

UPDATE: In addition to the above suggestion, as @Bahadir mentioned in the comment section below, you could also experiment with

material.depthWrite = false;

Version used: three.js r.77

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for extracting information from Firebase and showing it on a Google gauge chart

I'm having some trouble displaying data from Firebase on a gauge chart. I keep getting an error that says "Uncaught (in promise)". Here's the JavaScript code I've been working with: <script type="text/JavaScript"> google.ch ...

Differences Between React Prop Types and Typescript in Front-End

I'm considering incorporating TypeScript into my project. Would this render the use of prop-types in React unnecessary? With prop-types, I find myself having to manually define types, but TypeScript would eliminate this step. Am I on the right track? ...

Even after implementing a setTimeout function, both Promises and Axios requests are still resulting in a

Recently, I've encountered an issue with the Reverse Geocode API from TomTom. The problem arises when I send multiple latitude and longitude coordinates (around 72 of them) to the API, resulting in frequent 429 responses. To address this issue, I att ...

Donut and Bar Graph by Highchart

My goal is to create a chart similar to the one shown in the Example Image linked below. I have provided two separate plunkers for each type of chart. What I am aiming for: Example Image Donut Chart: ===> Refer to Comment section for Plunkr link // ...

How to access a particular tab in Bootstrap 5 using an external link

Is there a way to direct users to a specific tab upon clicking a link on another page? Check out the example below: <div class="products-btn"> <a href="products.html#pills-profile">view all</a> </div> On Pro ...

RectJs | Extract a parameter value from the url while disregarding any null values

Seeking assistance to retrieve the value of the "fruit" parameter from the URL in reactJs. Consider the following URL structure: http://localhost:3001/buy?fruit=&fruit=1&fruit=&fruit= Any of the four "fruit" parameters may contain a value, wi ...

Clear the cache in Angular to remove the page

Within my current project, I am utilizing angular's $routeProvider to dynamically load pages into an ng-view section. The loaded pages are displaying correctly in the ng-view and are being cached for quick access without needing to make a new server r ...

Change a reactive variable based on an event

I am currently working on a file upload feature in my application. Template.uploadFile.events({ 'change .set-file': function ( event, template ) { var file = event.currentTarget.files[0]; [...] } }); My goal is to read each row fro ...

Determining the live total number of Protovis Sparkbar instances

I am currently working on a project where I need to show the ratings and corresponding dates (in string format) from a JSON file in tipsy tooltips. The data consists of a list of dates and ratings. For example: var data = [{"dates":["2010-07-01","2010-07 ...

Are there any security risks in transmitting a password over HTTPS using jsonp?

Is it secure to send a password in JSONP using jquery over HTTPS for authentication if I can't use a JSON POST? EDIT: $.ajax({ type : "POST", url: "https://example.com/api.php", dataType: "jsonp", jsonp: "callback", data: { ...

Encountering an unidentified entity within a ReactJS application

Within a container, I've included a search bar inside a form element with two inputs - from and to, along with a submit button. Upon submitting the form, I create an OBJECT named query which looks like this: const query = { from : this.s ...

Creating default values for MongoDB databases using bdhash in Express.js and mongoose asynchronously

What is the best way to set a default value (like bdhash which is async) for a field in my mongoose schema? Currently, I am only seeing a promise inside. I'm using async/await correctly, but why does it seem like I'm getting just a promise? I als ...

Error: Unable to define $scope function in Angular and Jasmine integration

I am currently working with a controller var videoApp = angular.module('videoApp', ['videoAppFilters', 'ui.unique', 'angularUtils.directives.dirPagination']); videoApp.controller('VideoCtrl', function ($sc ...

Refine the Vuex state with a filter

Currently, I've progressed in my Vue development journey and started exploring the implementation of Vuex for state management. In the past, I had a main Vue component that handled search functionality, an array of items to iterate over, and the iter ...

Fetching data using JSONRequest sample code

I am new to web development and this is my first attempt at using JSON. On the JSON website (http://www.json.org/JSONRequest.html), they recommend using JSONRequest.get for certain tasks. However, I keep running into an error stating "JSONRequest is not ...

Identify a CSS style or attribute that is being dynamically assigned using JavaScript

While using the Jquery Cycle plugin for my slideshow, I'm looking to trigger an event when a specific slide is active. The Cycle plugin handles this by adjusting the opacity of images within a div in this manner: <div style="position: absolute; to ...

How can I set up automatic language selection for Google Translate's menu indexing feature?

My goal is to implement an automatic page translation feature using Google Translate's Library. I have been following the instructions provided in this link: The issue lies in the code snippet below, where the select menu creation works fine, but acc ...

The pencil-drawn pixel on the canvas is positioned off-center

Currently, I am using p5.js to draw pixels on canvas with a pencil tool. However, I have encountered an issue where the pixel does not appear centered when the size of the pencil is set to 1 or smaller. It seems to be offset towards the left or right. Upo ...

How can you gradually make a CSS border disappear?

Can an element's border fade away with the use of JavaScript only, without relying on jQuery for animation? We are currently working with Sencha and it seems that ExtJS only allows for animating element size and position. While CSS3 offers helpful ani ...

Revise the model and execute the function

When updating my model object, I am looking for a way to trigger a specific method. I have considered options such as: findOne modifying my properties calling the method on the object save Is there a way to achieve this using update or findOneAndUpdate ...