three#Color TypeScript Examples

The following examples show how to use three#Color. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ParticleSystem.tsx    From react-ecs with MIT License 6 votes vote down vote up
RandomColorSystem: FC = () => {
    useQuery(e => e.has(ThreeView), {
        added: ({ current }) => {
            const view = current.get(ThreeView);
            if (view) {
                const mesh = view.ref.current as Mesh;
                const material = mesh.material as MeshBasicMaterial;
                material.color?.set(
                    new Color(Math.random(), Math.random(), Math.random())
                );
            }
        }
    });

    return null;
}
Example #2
Source File: DebugProvider.ts    From geo-three with MIT License 6 votes vote down vote up
public fetchTile(zoom: number, x: number, y: number): Promise<any>
	{
		const canvas = CanvasUtils.createOffscreenCanvas(this.resolution, this.resolution);
		const context = canvas.getContext('2d');

		const green = new Color(0x00ff00);
		const red = new Color(0xff0000);

		const color = green.lerpHSL(red, (zoom - this.minZoom) / (this.maxZoom - this.minZoom));

		context.fillStyle = color.getStyle();
		context.fillRect(0, 0, this.resolution, this.resolution);

		context.fillStyle = '#000000';
		context.textAlign = 'center';
		context.textBaseline = 'middle';
		context.font = 'bold ' + this.resolution * 0.1 + 'px arial';
		context.fillText('(' + zoom + ')', this.resolution / 2, this.resolution * 0.4);
		context.fillText('(' + x + ', ' + y + ')', this.resolution / 2, this.resolution * 0.6);

		return Promise.resolve(canvas);
	}
Example #3
Source File: Fog.tsx    From spacesvr with MIT License 6 votes vote down vote up
export function Fog(props: FogProps) {
  const { color = "white", near = 10, far = 80 } = props;

  const scene = useThree((state) => state.scene);

  useEffect(() => {
    const col = (color as Color) instanceof Color ? color : new Color(color);
    scene.fog = new ThreeFog(col, near, far);

    return () => {
      scene.fog = null;
    };
  }, [scene, color, near, far]);

  return null;
}
Example #4
Source File: Background.tsx    From spacesvr with MIT License 6 votes vote down vote up
export function Background(props: BackgroundProps) {
  const { color } = props;

  const scene = useThree((state) => state.scene);

  useEffect(() => {
    const col = (color as Color) instanceof Color ? color : new Color(color);
    scene.background = col as Color;

    return () => {
      scene.background = null;
    };
  }, [color, scene]);

  return null;
}
Example #5
Source File: TextMeshObject.ts    From movy with MIT License 6 votes vote down vote up
constructor(params: TextMeshObjectParams = {}) {
    super();

    this.initParams = {
      centerTextVertically: false,
      color: new Color(0xffffff),
      font: 'en,zh',
      fontSize: 1.0,
      letterSpacing: 0,
      stroke: false,
      strokeWidth: 0.02,
      text3D: false,
      ...params,
    };

    if (this.initParams.material) {
      this.material = this.initParams.material.clone();
    } else {
      this.material = new MeshBasicMaterial({
        color: this.initParams.color,
        side: DoubleSide,
      });
    }
  }
Example #6
Source File: useWaterControls.ts    From THREE-CustomShaderMaterial with MIT License 6 votes vote down vote up
export default function useWaterControls(material: React.RefObject<CustomShaderMaterialType>) {
  useControls(
    'Water',
    () => ({
      Color: {
        value: '#52a7f7',
        onChange: (v) => {
          material.current!.uniforms.waterColor.value = new Color(v).convertLinearToSRGB()
        },
      },
      HighlightColor: {
        value: '#b3ffff',
        onChange: (v) => {
          material.current!.uniforms.waterHighlight.value = new Color(v).convertLinearToSRGB()
        },
      },

      Brightness: {
        value: 0.5,
        min: 0,
        max: 1,
        onChange: (v) => {
          material.current!.uniforms.brightness.value = v * 2
        },
      },
    }),
    [material]
  )
}
Example #7
Source File: scene-helper.ts    From head-tracked-3d with MIT License 5 votes vote down vote up
export function updateFog(scene: Scene) {
  const color = "black";

  if (!scene.fog) {
    scene.fog = new FogExp2(color, 0.05);
    scene.background = new Color(color);
  }
}
Example #8
Source File: Color.ts    From FairyGUI-threejs with MIT License 5 votes vote down vote up
export class Color4 extends Color {
    public a: number;

    public constructor(rgb?: number, a?: number) {
        super(rgb || 0);
        this.a = a != null ? a : 1;
    }
}
Example #9
Source File: color.ts    From movy with MIT License 5 votes vote down vote up
export function toThreeColor(color?: string | number): Color {
  return color === undefined
    ? new Color(0xffffff)
    : new Color(color).convertSRGBToLinear();
}
Example #10
Source File: NeighborDebugSystem.tsx    From react-ecs with MIT License 5 votes vote down vote up
material = new LineBasicMaterial( { color: new Color(
    Math.random(),
    Math.random(),
    Math.random(),
) } )
Example #11
Source File: HeightDebugProvider.d.ts    From geo-three with MIT License 5 votes vote down vote up
fromColor: Color;
Example #12
Source File: HeightDebugProvider.d.ts    From geo-three with MIT License 5 votes vote down vote up
toColor: Color;
Example #13
Source File: HeightDebugProvider.ts    From geo-three with MIT License 5 votes vote down vote up
/**
	 * Initial color to be used for lower values.
	 */
	public fromColor: Color = new Color(0xff0000);
Example #14
Source File: HeightDebugProvider.ts    From geo-three with MIT License 5 votes vote down vote up
/**
	 * Final color to be used for higher values.
	 */
	public toColor: Color = new Color(0x00ff00);
Example #15
Source File: Material.ts    From trois with MIT License 5 votes vote down vote up
BaseMaterial = defineComponent({
  emits: ['created'],
  props: {
    color: { type: String, default: '#ffffff' },
    props: { type: Object as PropType<MaterialPropsInterface>, default: () => ({}) },
  },
  inject: {
    mesh: MeshInjectionKey as symbol,
  },
  setup(): MaterialSetupInterface {
    return {}
  },
  provide() {
    return {
      [MaterialInjectionKey as symbol]: this,
    }
  },
  created() {
    if (!this.mesh) {
      console.error('Missing parent Mesh')
      return
    }

    if (this.createMaterial) {
      const material = this.material = this.createMaterial()
      // @ts-ignore
      watch(() => this.color, (value) => { material.color.set(value) })
      bindObjectProp(this, 'props', material, false, this.setProp)
      this.$emit('created', material)
      this.mesh.setMaterial(material)
    }
  },
  unmounted() {
    this.material?.dispose()
  },
  methods: {
    getMaterialParams() {
      return { ...propsValues(this.$props, ['props']), ...this.props }
    },
    setProp(material: any, key: string, value: any, needsUpdate = false) {
      const dstVal = material[key]
      if (dstVal instanceof Color) dstVal.set(value)
      else material[key] = value
      material.needsUpdate = needsUpdate
    },
    setTexture(texture: Texture | null, key = 'map') {
      this.setProp(this.material, key, texture, true)
    },
  },
  render() {
    return this.$slots.default ? this.$slots.default() : []
  },
  __hmrId: 'Material',
})
Example #16
Source File: SubsurfaceScatteringShader.ts    From trois with MIT License 5 votes vote down vote up
SubsurfaceScatteringShader = {

  uniforms: UniformsUtils.merge([
    ShaderLib.phong.uniforms,
    {
      thicknessColor: { value: new Color(0xffffff) },
      thicknessDistortion: { value: 0.1 },
      thicknessAmbient: { value: 0.0 },
      thicknessAttenuation: { value: 0.1 },
      thicknessPower: { value: 2.0 },
      thicknessScale: { value: 10.0 },
    },
  ]),

  vertexShader: `
    #define USE_UV
    ${ShaderChunk.meshphong_vert}
  `,

  fragmentShader: `
    #define USE_UV
    #define SUBSURFACE

    ${meshphongFragHead}

    uniform float thicknessPower;
    uniform float thicknessScale;
    uniform float thicknessDistortion;
    uniform float thicknessAmbient;
    uniform float thicknessAttenuation;
    uniform vec3 thicknessColor;

    void RE_Direct_Scattering(const in IncidentLight directLight, const in vec2 uv, const in GeometricContext geometry, inout ReflectedLight reflectedLight) {
      #ifdef USE_COLOR
        vec3 thickness = vColor * thicknessColor;
      #else
        vec3 thickness = thicknessColor;
      #endif
      vec3 scatteringHalf = normalize(directLight.direction + (geometry.normal * thicknessDistortion));
      float scatteringDot = pow(saturate(dot(geometry.viewDir, -scatteringHalf)), thicknessPower) * thicknessScale;
      vec3 scatteringIllu = (scatteringDot + thicknessAmbient) * thickness;
      reflectedLight.directDiffuse += scatteringIllu * thicknessAttenuation * directLight.color;
    }
  ` + meshphongFragBody.replace(
    '#include <lights_fragment_begin>',
    replaceAll(
      ShaderChunk.lights_fragment_begin,
      'RE_Direct( directLight, geometry, material, reflectedLight );',
      `
        RE_Direct( directLight, geometry, material, reflectedLight );
        #if defined( SUBSURFACE ) && defined( USE_UV )
          RE_Direct_Scattering(directLight, vUv, geometry, reflectedLight);
        #endif
      `
    )
  ),
}
Example #17
Source File: NMaterial.ts    From FairyGUI-threejs with MIT License 4 votes vote down vote up
public constructor() {
        super();

        let customUniforms = UniformsUtils.merge([
            ShaderLib.basic.uniforms,
            { _ColorMatrix: new Uniform(new Matrix4()) },
            { _ColorOffset: new Uniform(new Vector4()) },
            {
                diffuse: {
                    value: new Color(0xffffff)
                }
            }
        ]);

        this.uniforms = customUniforms;
        this.vertexShader = `
        #include <common>
        #include <uv_pars_vertex>
        #include <uv2_pars_vertex>
        #include <envmap_pars_vertex>
        varying vec4 vColor;
        attribute vec4 color;
        #include <fog_pars_vertex>
        #include <morphtarget_pars_vertex>
        #include <skinning_pars_vertex>
        #include <logdepthbuf_pars_vertex>
        #include <clipping_planes_pars_vertex>
        
        void main() {
        
            #include <uv_vertex>
            #include <uv2_vertex>

            vColor = color;

            #include <skinbase_vertex>
        
            #ifdef USE_ENVMAP
        
            #include <beginnormal_vertex>
            #include <morphnormal_vertex>
            #include <skinnormal_vertex>
            #include <defaultnormal_vertex>
        
            #endif
        
            #include <begin_vertex>
            #include <morphtarget_vertex>
            #include <skinning_vertex>
            #include <project_vertex>
            #include <logdepthbuf_vertex>
        
            #include <worldpos_vertex>
            #include <clipping_planes_vertex>
            #include <envmap_vertex>
            #include <fog_vertex>
        
        }
        `;

        this.fragmentShader = `
        uniform bool grayed;
        uniform bool colorFilter;
        uniform mat4 colorMatrix;
        uniform vec4 colorOffset;

        uniform vec3 diffuse;
        uniform float opacity;
        #ifndef FLAT_SHADED
            varying vec3 vNormal;
        #endif
        #include <common>
        #include <dithering_pars_fragment>

        varying vec4 vColor;

        #include <uv_pars_fragment>
        #include <uv2_pars_fragment>
        #include <map_pars_fragment>
        #include <alphamap_pars_fragment>
        #include <aomap_pars_fragment>
        #include <lightmap_pars_fragment>
        #include <envmap_common_pars_fragment>
        #include <envmap_pars_fragment>
        #include <cube_uv_reflection_fragment>
        #include <fog_pars_fragment>
        #include <specularmap_pars_fragment>
        #include <logdepthbuf_pars_fragment>
        #include <clipping_planes_pars_fragment>
        void main() {
            #include <clipping_planes_fragment>
            vec4 diffuseColor = vec4( diffuse, opacity );
            #include <logdepthbuf_fragment>
            #ifdef USE_MAP
                #ifdef TEXT
                    vec4 sampleColor = texture2D( map, vUv );
                    if(vColor.a<0.1)
                        diffuseColor.a *= sampleColor.r;
                    else if(vColor.a<0.4)
                        diffuseColor.a *= sampleColor.g;
                    else
                        diffuseColor.a *= sampleColor.b;
                #else
                    #include <map_fragment>
                #endif
            #endif

            #ifdef TEXT
            diffuseColor.rgb *= vColor.rgb;
            #else
            diffuseColor *= vColor;
            #endif

            #include <alphamap_fragment>
            #include <alphatest_fragment>
            #include <specularmap_fragment>
            ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
            // accumulation (baked indirect lighting only)
            #ifdef USE_LIGHTMAP
                vec4 lightMapTexel= texture2D( lightMap, vUv2 );
                reflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;
            #else
                reflectedLight.indirectDiffuse += vec3( 1.0 );
            #endif
            // modulation
            #include <aomap_fragment>
            reflectedLight.indirectDiffuse *= diffuseColor.rgb;
            vec3 outgoingLight = reflectedLight.indirectDiffuse;
            #include <envmap_fragment>
            gl_FragColor = vec4( outgoingLight, diffuseColor.a );
            #include <tonemapping_fragment>
            #include <encodings_fragment>
            #include <fog_fragment>
            #include <premultiplied_alpha_fragment>
            #include <dithering_fragment>

            #ifdef GRAYED
            float grey = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));
            gl_FragColor.rgb = vec3(grey, grey, grey);
            #endif

            #ifdef COLOR_FILTER
            vec4 col = gl_FragColor;
            gl_FragColor.r = dot(col, _ColorMatrix[0]) + _ColorOffset.x;
            gl_FragColor.g = dot(col, _ColorMatrix[1]) + _ColorOffset.y;
            gl_FragColor.b = dot(col, _ColorMatrix[2]) + _ColorOffset.z;
            gl_FragColor.a = dot(col, _ColorMatrix[3]) + _ColorOffset.w;
            #endif
        }
        `;

        this.name = "ui-material";
        this.lights = false;
        this.transparent = true;
        this.depthTest = false;
        this.side = DoubleSide;
        //this.wireframe = true;
        this["isMeshBasicMaterial"] = true;
    }