<template>
  <div>
    <div>
    <button @click="increment">步数: {{ count }}</button>
    <button @click="inOpacity">透明度： {{ opacity }}</button>
    </div>
    <div id="vtkContainer" />
   
  </div>
</template >

<script setup>
import * as d3 from 'd3-scale';
import { formatDefaultLocale } from 'd3-format';
import { ref,onMounted } from 'vue';
import '@kitware/vtk.js/Rendering/Profiles/Geometry';
import vtkRenderWindowWithControlBar from '@kitware/vtk.js/Rendering/Misc/RenderWindowWithControlBar';
import vtkFullScreenRenderWindow from '@kitware/vtk.js/Rendering/Misc/FullScreenRenderWindow';
import vtkActor           from '@kitware/vtk.js/Rendering/Core/Actor';
import vtkMapper          from '@kitware/vtk.js/Rendering/Core/Mapper';
import vtkUnstructuredDataReader from '../reader/UnstructuredDataReader.js';
import vtkScalarBarActor from '@kitware/vtk.js/Rendering/Core/ScalarBarActor';
import vtkLookupTable from '@kitware/vtk.js/Common/Core/LookupTable';
import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray.js';
import vtkColorTransferFunction from '@kitware/vtk.js/Rendering/Core/ColorTransferFunction';
// 响应式状态
const count = ref(0);//步数
const opacity = ref(0.1);
const min=ref(0.0);
const max=ref(1.0);

const scalarFAll = ref([]);//火灾标量
const scalarWAll = ref([]);//水灾标量
const foW =ref(false);//火灾 true  水灾 false
/*
  Temperature：温度
  Pressure：压强
  SO2：SO2
  CO2：CO2
  Height：水位高度
*/

const scalarName = ref("CO2");
const filedir =ref("data/Fire/");
//const scalarName = ref("Height");
//const filedir =ref("data/Water/"); 
const renderWindowWith = vtkRenderWindowWithControlBar.newInstance({
    controlSize: 2,
  });
// const renderWindowWith =vtkFullScreenRenderWindow.newInstance();
const renderer = renderWindowWith.getRenderer();
// renderer.setBackground([0.1,0.2,0]); 
const renderWindow = renderWindowWith.getRenderWindow();
const resetCamera = renderer.resetCamera;
const render = renderWindow.render;
const mapper = vtkMapper.newInstance();
//Sets scalarMode to USE_POINT_DATA
// mapper.setScalarModeToUsePointData();
const actor = vtkActor.newInstance();
const reader = vtkUnstructuredDataReader.newInstance();

// 设置透明度
function inOpacity() {
  opacity.value=opacity.value+0.1;
  actor.getProperty().setOpacity(opacity.value);
  renderWindow.render();
}
//计算最大最小值
function getMinMax(scalars){
  // console.log("getMinMax:",scalars);
       min.value=scalars[0];
       max.value=scalars[0];
  for (let index = 0; index <= scalars.length; index++) {
    let scalar=scalars[index];
     if(min.value>scalar){
        min.value=scalar;
      }
      if(max.value<scalar){
        max.value=scalar;
      }
  }
  // console.log("max，min:",max.value,min.value);
}
// 用来修改状态、触发更新的函数
function increment() {
  count.value++;
  var scalars;
  if(foW.value){
       scalars=scalarFAll.value[count.value];
  }else{
       scalars=scalarWAll.value[count.value];
  }
  const polydata = mapper.getInputData();      
  const scalarArray=scalars.get(scalarName.value);
  // console.log("scalarArray:",scalarArray);
  const dataArray = vtkDataArray.newInstance({
    name:scalarName.value,
    size:polydata.getNumberOfPoints()
  }); 
  dataArray.setData(scalarArray);
  polydata.getPointData().setScalars(dataArray); 
 
  mapper.clearColorArrays();//强制重建颜色
  actor.getProperty().setOpacity(count.value+2);//设置错误的透明度使得页面重新加载  不设置不刷新页面
  renderWindow.render();
}
//加载所有 标量数据
function loadScalarAll(){
  //水灾
 for (let index = 0; index <= 60; index++) {
    const reader = vtkUnstructuredDataReader.newInstance();
    reader.setUrl("data/Water/"+'POST'+index+'.vtk').then(() => {
    const scalars = reader.getOutputData(1);
    scalarWAll.value[index]=scalars;
    });
  }
  //火灾
  for (let index = 0; index <= 60; index++) {
    const reader = vtkUnstructuredDataReader.newInstance();
    reader.setUrl("data/Fire/"+'POST'+index+'.vtk').then(() => {
    const scalars = reader.getOutputData(1);
    scalarFAll.value[index]=scalars;
    });
  }
}
//设置 
function generateTicks(numberOfTicks) {
  return (helper) => {
    const lastTickBounds = helper.getLastTickBounds();
    // compute tick marks for axes
    const scale = d3
      .scaleLinear()
      .domain([0.0, 1.0])
      .range([lastTickBounds[0], lastTickBounds[1]]);
    const samples = scale.ticks(numberOfTicks);
    const ticks = samples.map((tick) => scale(tick));
    // Replace minus "\u2212" with hyphen-minus "\u002D" so that parseFloat() works
    formatDefaultLocale({ minus: '\u002D' });
    const format = scale.tickFormat(
      ticks[0],
      ticks[ticks.length - 1],
      numberOfTicks
    );
    const tickStrings = ticks
      .map(format)
      .map((tick) => Number(parseFloat(tick).toPrecision(12)).toPrecision()); // d3 sometimes adds unwanted whitespace
    helper.setTicks(ticks);
    helper.setTickStrings(tickStrings);
  };     
}
//安装时
onMounted(() => {
  //div 绑定
  const rootContainer =document.getElementById("vtkContainer");
  rootContainer.style.position = 'relative';
  rootContainer.style.width = '1000px';
  rootContainer.style.height = '500px';
  console.log("rootContainer:",rootContainer);    
 
  renderWindowWith.setContainer(rootContainer);
  // fullScreenRenderer.setBackground([0,0,0]);
  // const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance();
  reader.setUrl(filedir.value+'POST0.vtk').then(() => {
    const polydata = reader.getOutputData(0);        
    const scalars = reader.getOutputData(1);    
    const scalarArray=scalars.get(scalarName.value);
    // console.log("scalarArray:",scalarArray);
    const dataArray = vtkDataArray.newInstance({
      name:scalarName.value,
      size:polydata.getNumberOfPoints()
    });
    dataArray.setData(scalarArray);
    polydata.getPointData().setScalars(dataArray); 
    actor.setMapper(mapper);
    mapper.setInputData(polydata);
    getMinMax(scalarArray);
    mapper.setScalarRange(min.value,max.value);//设置范围

    renderer.addActor(actor);

    let lut = mapper.getLookupTable();
    const scalarBarActor = vtkScalarBarActor.newInstance();
    renderer.addActor(scalarBarActor);
    scalarBarActor.setScalarsToColors(lut);
    // console.log("lut:",lut.getRange());    
    // Change the number of ticks (TODO: add numberOfTicks to ScalarBarActor)
    scalarBarActor.setGenerateTicks(generateTicks(5));
    scalarBarActor.setAxisLabel(scalarName.value);
    scalarBarActor.setDrawAboveRangeSwatch(true);
    
    //修改设条颜色
    const ctf = vtkColorTransferFunction.newInstance();
    ctf.addRGBPoint(0.0, 0.0, 0.0, 1.0);
    ctf.addRGBPoint(1.0, 0.0, 1.0, 0.5);
    ctf.addRGBPoint(2.0, 0.0, 1.0, 0.0);
    ctf.addRGBPoint(3.0, 1.0, 0.5, 0.0);
    ctf.addRGBPoint(4.0, 1.0, 0.0, 0.0);
    mapper.setLookupTable(ctf);
    // lut = mapper.getLookupTable();
    // scalarBarActor.setScalarsToColors(lut);
    resetCamera();
   renderWindow.render();
  });
  loadScalarAll();
});
</script>

<style scoped>
</style>