Хорошо, я разбиваю пример ShaderGlow из https://github.com/stemkoski/stemkoski.github.com/blob/master/Three.js/Shader-Glow.html, пытаясь перенести его в свое приложение узла.
Автор делает все в тегах в html-документе, но все мое приложение находится в app.js и вызывает модули ES6 из вспомогательных файлов.
Шейдер до моей настройки работает так:
var customMaterial = new THREE.ShaderMaterial(
{
uniforms:
{
"c": { type: "f", value: 1.0 },
"p": { type: "f", value: 1.4 },
glowColor: { type: "c", value: new THREE.Color(0xffff00) },
viewVector: { type: "v3", value: camera.position }
},
vertexShader: document.getElementById( 'vertexShader' ).textContent,
fragmentShader: document.getElementById( 'fragmentShader' ).textContent,
side: THREE.FrontSide,
blending: THREE.AdditiveBlending,
transparent: true
} );
Где фрагмент и вершинный шейдер находятся в своих собственных:
<!-- ---------------- Custom Shader Code ------------------------ -->
<script id = "vertexShader" type = "x-shader/x-vertex">
uniform vec3 viewVector;
uniform float c;
uniform float p;
varying float intensity;
void main()
{
vec3 vNormal = normalize( normalMatrix * normal );
vec3 vNormel = normalize( normalMatrix * viewVector );
intensity = pow( c - dot(vNormal, vNormel), p );
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
</script>
<!-- fragment shader a.k.a. pixel shader -->
<script id = "fragmentShader" type = "x-shader/x-vertex">
uniform vec3 glowColor;
varying float intensity;
void main()
{
vec3 glow = glowColor * intensity;
gl_FragColor = vec4( glow, 1.0 );
}
</script>
До сих пор я пытался сделать:
import fragmentShader from './elements/GlowShaders.js';
import vertexShader from './elements/GlowShaders.js';
var customMaterial = new THREE.ShaderMaterial(
{
uniforms:
{
"c": { type: "f", value: 1.0 },
"p": { type: "f", value: 1.4 },
glowColor: { type: "c", value: new THREE.Color(0xffff00) },
viewVector: { type: "v3", value: this.camera.position }
},
vertexShader: vertexShader,
fragmentShader: fragmentShader,
side: THREE.FrontSide,
blending: THREE.AdditiveBlending,
transparent: true
} );
С GlowShader.js написано так:
export default class vertexShader {
uniform vec3 viewVector;
uniform float c;
uniform float p;
varying float intensity;
void main()
{
vec3 vNormal = normalize( normalMatrix * normal );
vec3 vNormel = normalize( normalMatrix * viewVector );
intensity = pow( c - dot(vNormal, vNormel), p );
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
}
export default class fragmentShader {
uniform vec3 glowColor;
varying float intensity;
constructor() {
vec3 glow = glowColor * intensity;
gl_FragColor = vec4( glow, 1.0 );
}
}
Честно говоря, очень новичок в модулях, и это не работает. Как я могу разбить эти специальные блоки шейдера на модули или включить их в свой скрипт app.js?
проверить шадертой
@ Томас, приятно знать. Как тогда я могу включить только текст? Учитывая, что я не работаю с тегами <script>?
Как поместить строку в некоторый код JS?
@Thomas Что мне просто вставить весь блок кода шейдера в кавычки после параметра «vertexShader:» в customMaterial?
да, но я бы либо использовал строки шаблона, либо использовал JSON.stringify() для правильной сериализации этой многострочной строки. Но это именно то, что делает vertexShader: document.getElementById( 'vertexShader' ).textContent. * Найдите узел скрипта с идентификатором "vertexShader", получите textContent этого узла и передайте этот текст свойству vertexShader
Можете ли вы предоставить ответ, где вы помещаете блок кода в JSON.stringify или другой формат, который может быть прочитан JS? Вставка прямо в параметр не работает, нет



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Can you provide an answer where you put the code block into JSON.stringify or another format able to be read by the JS? Pasting straight into the parameter doesn't work, no.
const vertexShader = `
uniform vec3 viewVector;
uniform float c;
uniform float p;
varying float intensity;
void main()
{
vec3 vNormal = normalize( normalMatrix * normal );
vec3 vNormel = normalize( normalMatrix * viewVector );
intensity = pow( c - dot(vNormal, vNormel), p );
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`;
const fragmentShader = `
uniform vec3 glowColor;
varying float intensity;
void main()
{
vec3 glow = glowColor * intensity;
gl_FragColor = vec4( glow, 1.0 );
}`;
var customMaterial = new THREE.ShaderMaterial({
uniforms:
{
"c": { type: "f", value: 1.0 },
"p": { type: "f", value: 1.4 },
glowColor: { type: "c", value: new THREE.Color(0xffff00) },
viewVector: { type: "v3", value: camera.position }
},
vertexShader,
fragmentShader,
side: THREE.FrontSide,
blending: THREE.AdditiveBlending,
transparent: true
});
или
var customMaterial = new THREE.ShaderMaterial({
uniforms:
{
"c": { type: "f", value: 1.0 },
"p": { type: "f", value: 1.4 },
glowColor: { type: "c", value: new THREE.Color(0xffff00) },
viewVector: { type: "v3", value: camera.position }
},
vertexShader: "uniform vec3 viewVector;\nuniform float c;\nuniform float p;\nvarying float intensity;\nvoid main() \n{\n vec3 vNormal = normalize( normalMatrix * normal );\n vec3 vNormel = normalize( normalMatrix * viewVector );\n intensity = pow( c - dot(vNormal, vNormel), p );\n\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",
fragmentShader: "uniform vec3 glowColor;\nvarying float intensity;\nvoid main() \n{\n vec3 glow = glowColor * intensity;\n gl_FragColor = vec4( glow, 1.0 );\n}",
side: THREE.FrontSide,
blending: THREE.AdditiveBlending,
transparent: true
});
Шейдеры — это отдельный язык. Они не JS. Это код, который выполняется на вашей видеокарте. Вы должны передавать скрипты шейдеров точно так же, как они есть, в three.js (в виде строк).