copy warp3DMapImage in the project and make some changes
parent
0ffec7b104
commit
df5028dacf
|
@ -19,10 +19,13 @@
|
|||
<Reference name="Nini.dll" path="../../../bin"/>
|
||||
<Reference name="log4net.dll" path="../../../bin"/>
|
||||
<Reference name="XMLRPC.dll" path="../../../bin"/>
|
||||
<Reference name="CSJ2K.dll" path="../../../bin"/>
|
||||
<Reference name="Warp3D.dll" path="../../../bin"/>
|
||||
<Reference name="Mono.Addins.dll" path="../../../bin"/>
|
||||
<Reference name="Mono.Security.dll" path="../../../bin"/>
|
||||
<Reference name="OpenMetaverseTypes.dll" path="../../../bin"/>
|
||||
<Reference name="OpenSim.Region.PhysicsModules.SharedBase.dll" path="../../../bin"/>
|
||||
<Reference name="OpenMetaverse.dll" path="../../../bin"/>
|
||||
<Reference name="OpenMetaverse.StructuredData.dll" path="../../../bin"/>
|
||||
<Reference name="HttpServer_OpenSim.dll" path="../../../bin"/>
|
||||
<Reference name="OpenSim.Region.Framework" path="../../../bin"/>
|
||||
<Reference name="OpenSim.Framework" path="../../../bin"/>
|
||||
|
@ -32,6 +35,7 @@
|
|||
<Reference name="OpenSim.Services.Interfaces" path="../../../bin"/>
|
||||
<Reference name="OpenSim.Server.Base" path="../../../bin"/>
|
||||
<Reference name="OpenSim.Data" path="../../../bin"/>
|
||||
|
||||
<Files>
|
||||
<Match pattern="*.cs" recurse="true"/>
|
||||
</Files>
|
||||
|
|
|
@ -0,0 +1,214 @@
|
|||
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
|
||||
<PropertyGroup>
|
||||
<ProjectType>Local</ProjectType>
|
||||
<ProductVersion>9.0.30729</ProductVersion>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
<ProjectGuid>{D5EA1308-0000-0000-0000-000000000000}</ProjectGuid>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<ApplicationIcon></ApplicationIcon>
|
||||
<AssemblyKeyContainerName>
|
||||
</AssemblyKeyContainerName>
|
||||
<AssemblyName>OpenSim.Modules.Warp3DCachedImageModule</AssemblyName>
|
||||
<DefaultClientScript>JScript</DefaultClientScript>
|
||||
<DefaultHTMLPageLayout>Grid</DefaultHTMLPageLayout>
|
||||
<DefaultTargetSchema>IE50</DefaultTargetSchema>
|
||||
<DelaySign>false</DelaySign>
|
||||
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder></AppDesignerFolder>
|
||||
<RootNamespace>OpenSim.Modules.Warp3DCachedImageModule</RootNamespace>
|
||||
<StartupObject></StartupObject>
|
||||
<StartArguments></StartArguments>
|
||||
<FileUpgradeFlags>
|
||||
</FileUpgradeFlags>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
|
||||
<BaseAddress>285212672</BaseAddress>
|
||||
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
|
||||
<ConfigurationOverrideFile>
|
||||
</ConfigurationOverrideFile>
|
||||
<DefineConstants>TRACE;DEBUG</DefineConstants>
|
||||
<DocumentationFile></DocumentationFile>
|
||||
<DebugSymbols>True</DebugSymbols>
|
||||
<FileAlignment>4096</FileAlignment>
|
||||
<Optimize>False</Optimize>
|
||||
<OutputPath>..\..\..\bin\</OutputPath>
|
||||
<RegisterForComInterop>False</RegisterForComInterop>
|
||||
<RemoveIntegerChecks>False</RemoveIntegerChecks>
|
||||
<TreatWarningsAsErrors>False</TreatWarningsAsErrors>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<NoStdLib>False</NoStdLib>
|
||||
<NoWarn></NoWarn>
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
|
||||
<BaseAddress>285212672</BaseAddress>
|
||||
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
|
||||
<ConfigurationOverrideFile>
|
||||
</ConfigurationOverrideFile>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<DocumentationFile></DocumentationFile>
|
||||
<DebugSymbols>False</DebugSymbols>
|
||||
<FileAlignment>4096</FileAlignment>
|
||||
<Optimize>True</Optimize>
|
||||
<OutputPath>..\..\..\bin\</OutputPath>
|
||||
<RegisterForComInterop>False</RegisterForComInterop>
|
||||
<RemoveIntegerChecks>False</RemoveIntegerChecks>
|
||||
<TreatWarningsAsErrors>False</TreatWarningsAsErrors>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<NoStdLib>False</NoStdLib>
|
||||
<NoWarn></NoWarn>
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Axiom.MathLib.dll" >
|
||||
<Name>Axiom.MathLib.dll</Name>
|
||||
<HintPath>..\..\bin\Axiom.MathLib.dll</HintPath>
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="CSJ2K.dll" >
|
||||
<Name>CSJ2K.dll</Name>
|
||||
<HintPath>..\..\..\bin\CSJ2K.dll</HintPath>
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="HttpServer_OpenSim.dll" >
|
||||
<Name>HttpServer_OpenSim.dll</Name>
|
||||
<HintPath>..\..\..\bin\HttpServer_OpenSim.dll</HintPath>
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="log4net.dll" >
|
||||
<Name>log4net.dll</Name>
|
||||
<HintPath>..\..\..\bin\log4net.dll</HintPath>
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="Mono.Addins.dll" >
|
||||
<Name>Mono.Addins.dll</Name>
|
||||
<HintPath>..\..\..\bin\Mono.Addins.dll</HintPath>
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="Nini.dll" >
|
||||
<Name>Nini.dll</Name>
|
||||
<HintPath>..\..\..\bin\Nini.dll</HintPath>
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="OpenMetaverse.dll" >
|
||||
<Name>OpenMetaverse.dll</Name>
|
||||
<HintPath>..\..\..\bin\OpenMetaverse.dll</HintPath>
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="OpenMetaverse.StructuredData.dll" >
|
||||
<Name>OpenMetaverse.StructuredData.dll</Name>
|
||||
<HintPath>..\..\..\bin\OpenMetaverse.StructuredData.dll</HintPath>
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="OpenMetaverseTypes.dll" >
|
||||
<Name>OpenMetaverseTypes.dll</Name>
|
||||
<HintPath>..\..\..\bin\OpenMetaverseTypes.dll</HintPath>
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="OpenSim.Region.PhysicsModules.SharedBase.dll" >
|
||||
<Name>OpenSim.Region.PhysicsModules.SharedBase.dll</Name>
|
||||
<HintPath>..\..\..\bin\OpenSim.Region.PhysicsModules.SharedBase.dll</HintPath>
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="System" >
|
||||
<Name>System</Name>
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="System.Drawing" >
|
||||
<Name>System.Drawing</Name>
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="System.Runtime.Remoting" >
|
||||
<Name>System.Runtime.Remoting</Name>
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="System.Xml" >
|
||||
<Name>System.Xml</Name>
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="Warp3D.dll" >
|
||||
<Name>Warp3D.dll</Name>
|
||||
<HintPath>..\..\..\bin\Warp3D.dll</HintPath>
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="XMLRPC.dll" >
|
||||
<Name>XMLRPC.dll</Name>
|
||||
<HintPath>..\..\..\bin\XMLRPC.dll</HintPath>
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\OpenSim\Data\OpenSim.Data.csproj">
|
||||
<Name>OpenSim.Data</Name>
|
||||
<Project>{7E218E2D-0000-0000-0000-000000000000}</Project>
|
||||
<Package>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</Package>
|
||||
<Private>False</Private>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\..\..\OpenSim\Framework\OpenSim.Framework.csproj">
|
||||
<Name>OpenSim.Framework</Name>
|
||||
<Project>{BCCDBB55-0000-0000-0000-000000000000}</Project>
|
||||
<Package>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</Package>
|
||||
<Private>False</Private>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\..\..\OpenSim\Framework\Console\OpenSim.Framework.Console.csproj">
|
||||
<Name>OpenSim.Framework.Console</Name>
|
||||
<Project>{0ED8EBE8-0000-0000-0000-000000000000}</Project>
|
||||
<Package>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</Package>
|
||||
<Private>False</Private>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\..\..\OpenSim\Framework\Servers\OpenSim.Framework.Servers.csproj">
|
||||
<Name>OpenSim.Framework.Servers</Name>
|
||||
<Project>{726D540D-0000-0000-0000-000000000000}</Project>
|
||||
<Package>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</Package>
|
||||
<Private>False</Private>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\..\..\OpenSim\Framework\Servers\HttpServer\OpenSim.Framework.Servers.HttpServer.csproj">
|
||||
<Name>OpenSim.Framework.Servers.HttpServer</Name>
|
||||
<Project>{159EC5C2-0000-0000-0000-000000000000}</Project>
|
||||
<Package>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</Package>
|
||||
<Private>False</Private>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\..\..\OpenSim\Region\Framework\OpenSim.Region.Framework.csproj">
|
||||
<Name>OpenSim.Region.Framework</Name>
|
||||
<Project>{C98F6D97-0000-0000-0000-000000000000}</Project>
|
||||
<Package>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</Package>
|
||||
<Private>False</Private>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\..\..\OpenSim\Server\Base\OpenSim.Server.Base.csproj">
|
||||
<Name>OpenSim.Server.Base</Name>
|
||||
<Project>{2E0569BB-0000-0000-0000-000000000000}</Project>
|
||||
<Package>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</Package>
|
||||
<Private>False</Private>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\..\..\OpenSim\Services\Interfaces\OpenSim.Services.Interfaces.csproj">
|
||||
<Name>OpenSim.Services.Interfaces</Name>
|
||||
<Project>{08ECE473-0000-0000-0000-000000000000}</Project>
|
||||
<Package>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</Package>
|
||||
<Private>False</Private>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Perlin.cs">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="TerrainSplat.cs">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="Viewport.cs">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="Warp3DImageModule.cs">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildBinPath)\Microsoft.CSHARP.Targets" />
|
||||
<PropertyGroup>
|
||||
<PreBuildEvent>
|
||||
</PreBuildEvent>
|
||||
<PostBuildEvent>
|
||||
</PostBuildEvent>
|
||||
</PropertyGroup>
|
||||
</Project>
|
|
@ -0,0 +1,63 @@
|
|||
<?xml version="1.0" ?>
|
||||
<project name="OpenSim.Modules.Warp3DCachedImageModule" default="build">
|
||||
<target name="build">
|
||||
<echo message="Build Directory is ${project::get-base-directory()}/${build.dir}" />
|
||||
<mkdir dir="${project::get-base-directory()}/${build.dir}" />
|
||||
<csc target="library" debug="${build.debug}" platform="${build.platform}" unsafe="True" warnaserror="False" define="TRACE;DEBUG" nostdlib="False" main="" output="${project::get-base-directory()}/${build.dir}/${project::get-name()}.dll" noconfig="true">
|
||||
<resources prefix="OpenSim.Modules.Warp3DCachedImageModule" dynamicprefix="true" >
|
||||
</resources>
|
||||
<sources failonempty="true">
|
||||
<include name="Perlin.cs" />
|
||||
<include name="TerrainSplat.cs" />
|
||||
<include name="Viewport.cs" />
|
||||
<include name="Warp3DImageModule.cs" />
|
||||
</sources>
|
||||
<references basedir="${project::get-base-directory()}">
|
||||
<lib>
|
||||
<include name="${project::get-base-directory()}" />
|
||||
<include name="${project::get-base-directory()}/../../../bin" />
|
||||
</lib>
|
||||
<include name="../../binAxiom.MathLib.dll"/>
|
||||
<include name="../../../binCSJ2K.dll"/>
|
||||
<include name="../../../binHttpServer_OpenSim.dll"/>
|
||||
<include name="../../../binlog4net.dll"/>
|
||||
<include name="../../../binMono.Addins.dll"/>
|
||||
<include name="../../../binNini.dll"/>
|
||||
<include name="../../../binOpenMetaverse.dll"/>
|
||||
<include name="../../../binOpenMetaverse.StructuredData.dll"/>
|
||||
<include name="../../../binOpenMetaverseTypes.dll"/>
|
||||
<include name="../../../binOpenSim.Data.dll"/>
|
||||
<include name="../../../binOpenSim.Framework.dll"/>
|
||||
<include name="../../../binOpenSim.Framework.Console.dll"/>
|
||||
<include name="../../../binOpenSim.Framework.Servers.dll"/>
|
||||
<include name="../../../binOpenSim.Framework.Servers.HttpServer.dll"/>
|
||||
<include name="../../../binOpenSim.Region.Framework.dll"/>
|
||||
<include name="../../../binOpenSim.Region.PhysicsModules.SharedBase.dll"/>
|
||||
<include name="../../../binOpenSim.Server.Base.dll"/>
|
||||
<include name="../../../binOpenSim.Services.Interfaces.dll"/>
|
||||
<include name="System.dll" />
|
||||
<include name="System.Drawing.dll" />
|
||||
<include name="System.Runtime.Remoting.dll" />
|
||||
<include name="System.Xml.dll" />
|
||||
<include name="../../../binWarp3D.dll"/>
|
||||
<include name="../../../binXMLRPC.dll"/>
|
||||
</references>
|
||||
</csc>
|
||||
<echo message="Copying from [${project::get-base-directory()}/${build.dir}/] to [${project::get-base-directory()}/../../../bin" />
|
||||
<mkdir dir="${project::get-base-directory()}/../../../bin"/>
|
||||
<copy todir="${project::get-base-directory()}/../../../bin">
|
||||
<fileset basedir="${project::get-base-directory()}/${build.dir}/" >
|
||||
<include name="*.dll"/>
|
||||
<include name="*.exe"/>
|
||||
<include name="*.mdb" if='${build.debug}'/>
|
||||
<include name="*.pdb" if='${build.debug}'/>
|
||||
</fileset>
|
||||
</copy>
|
||||
</target>
|
||||
<target name="clean">
|
||||
<delete dir="${bin.dir}" failonerror="false" />
|
||||
<delete dir="${obj.dir}" failonerror="false" />
|
||||
</target>
|
||||
<target name="doc" description="Creates documentation.">
|
||||
</target>
|
||||
</project>
|
|
@ -0,0 +1,271 @@
|
|||
/*
|
||||
* Copyright (c) Contributors, http://opensimulator.org/
|
||||
* See CONTRIBUTORS.TXT for a full list of copyright holders.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of the OpenSimulator Project nor the
|
||||
* names of its contributors may be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
|
||||
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using OpenMetaverse;
|
||||
|
||||
namespace OpenSim.Region.CoreModules.World.Warp3DMap
|
||||
{
|
||||
public static class Perlin
|
||||
{
|
||||
// We use a hardcoded seed to keep the noise generation consistent between runs
|
||||
private const int SEED = 42;
|
||||
|
||||
private const int SAMPLE_SIZE = 1024;
|
||||
private const int B = SAMPLE_SIZE;
|
||||
private const int BM = SAMPLE_SIZE - 1;
|
||||
private const int N = 0x1000;
|
||||
|
||||
private static readonly int[] p = new int[SAMPLE_SIZE + SAMPLE_SIZE + 2];
|
||||
private static readonly float[,] g3 = new float[SAMPLE_SIZE + SAMPLE_SIZE + 2, 3];
|
||||
private static readonly float[,] g2 = new float[SAMPLE_SIZE + SAMPLE_SIZE + 2, 2];
|
||||
private static readonly float[] g1 = new float[SAMPLE_SIZE + SAMPLE_SIZE + 2];
|
||||
|
||||
static Perlin()
|
||||
{
|
||||
Random rng = new Random(SEED);
|
||||
int i, j, k;
|
||||
|
||||
for (i = 0; i < B; i++)
|
||||
{
|
||||
p[i] = i;
|
||||
g1[i] = (float)((rng.Next() % (B + B)) - B) / B;
|
||||
|
||||
for (j = 0; j < 2; j++)
|
||||
g2[i, j] = (float)((rng.Next() % (B + B)) - B) / B;
|
||||
normalize2(g2, i);
|
||||
|
||||
for (j = 0; j < 3; j++)
|
||||
g3[i, j] = (float)((rng.Next() % (B + B)) - B) / B;
|
||||
normalize3(g3, i);
|
||||
}
|
||||
|
||||
while (--i > 0)
|
||||
{
|
||||
k = p[i];
|
||||
p[i] = p[j = rng.Next() % B];
|
||||
p[j] = k;
|
||||
}
|
||||
|
||||
for (i = 0; i < B + 2; i++)
|
||||
{
|
||||
p[B + i] = p[i];
|
||||
g1[B + i] = g1[i];
|
||||
for (j = 0; j < 2; j++)
|
||||
g2[B + i, j] = g2[i, j];
|
||||
for (j = 0; j < 3; j++)
|
||||
g3[B + i, j] = g3[i, j];
|
||||
}
|
||||
}
|
||||
|
||||
public static float noise1(float arg)
|
||||
{
|
||||
int bx0, bx1;
|
||||
float rx0, rx1, sx, t, u, v;
|
||||
|
||||
t = arg + N;
|
||||
bx0 = ((int)t) & BM;
|
||||
bx1 = (bx0 + 1) & BM;
|
||||
rx0 = t - (int)t;
|
||||
rx1 = rx0 - 1f;
|
||||
|
||||
sx = s_curve(rx0);
|
||||
|
||||
u = rx0 * g1[p[bx0]];
|
||||
v = rx1 * g1[p[bx1]];
|
||||
|
||||
return Utils.Lerp(u, v, sx);
|
||||
}
|
||||
|
||||
public static float noise2(float x, float y)
|
||||
{
|
||||
int bx0, bx1, by0, by1, b00, b10, b01, b11;
|
||||
float rx0, rx1, ry0, ry1, sx, sy, a, b, t, u, v;
|
||||
int i, j;
|
||||
|
||||
t = x + N;
|
||||
bx0 = ((int)t) & BM;
|
||||
bx1 = (bx0 + 1) & BM;
|
||||
rx0 = t - (int)t;
|
||||
rx1 = rx0 - 1f;
|
||||
|
||||
t = y + N;
|
||||
by0 = ((int)t) & BM;
|
||||
by1 = (by0 + 1) & BM;
|
||||
ry0 = t - (int)t;
|
||||
ry1 = ry0 - 1f;
|
||||
|
||||
i = p[bx0];
|
||||
j = p[bx1];
|
||||
|
||||
b00 = p[i + by0];
|
||||
b10 = p[j + by0];
|
||||
b01 = p[i + by1];
|
||||
b11 = p[j + by1];
|
||||
|
||||
sx = s_curve(rx0);
|
||||
sy = s_curve(ry0);
|
||||
|
||||
u = rx0 * g2[b00, 0] + ry0 * g2[b00, 1];
|
||||
v = rx1 * g2[b10, 0] + ry0 * g2[b10, 1];
|
||||
a = Utils.Lerp(u, v, sx);
|
||||
|
||||
u = rx0 * g2[b01, 0] + ry1 * g2[b01, 1];
|
||||
v = rx1 * g2[b11, 0] + ry1 * g2[b11, 1];
|
||||
b = Utils.Lerp(u, v, sx);
|
||||
|
||||
return Utils.Lerp(a, b, sy);
|
||||
}
|
||||
|
||||
public static float noise3(float x, float y, float z)
|
||||
{
|
||||
int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11;
|
||||
float rx0, rx1, ry0, ry1, rz0, rz1, sy, sz, a, b, c, d, t, u, v;
|
||||
int i, j;
|
||||
|
||||
t = x + N;
|
||||
bx0 = ((int)t) & BM;
|
||||
bx1 = (bx0 + 1) & BM;
|
||||
rx0 = t - (int)t;
|
||||
rx1 = rx0 - 1f;
|
||||
|
||||
t = y + N;
|
||||
by0 = ((int)t) & BM;
|
||||
by1 = (by0 + 1) & BM;
|
||||
ry0 = t - (int)t;
|
||||
ry1 = ry0 - 1f;
|
||||
|
||||
t = z + N;
|
||||
bz0 = ((int)t) & BM;
|
||||
bz1 = (bz0 + 1) & BM;
|
||||
rz0 = t - (int)t;
|
||||
rz1 = rz0 - 1f;
|
||||
|
||||
i = p[bx0];
|
||||
j = p[bx1];
|
||||
|
||||
b00 = p[i + by0];
|
||||
b10 = p[j + by0];
|
||||
b01 = p[i + by1];
|
||||
b11 = p[j + by1];
|
||||
|
||||
t = s_curve(rx0);
|
||||
sy = s_curve(ry0);
|
||||
sz = s_curve(rz0);
|
||||
|
||||
u = rx0 * g3[b00 + bz0, 0] + ry0 * g3[b00 + bz0, 1] + rz0 * g3[b00 + bz0, 2];
|
||||
v = rx1 * g3[b10 + bz0, 0] + ry0 * g3[b10 + bz0, 1] + rz0 * g3[b10 + bz0, 2];
|
||||
a = Utils.Lerp(u, v, t);
|
||||
|
||||
u = rx0 * g3[b01 + bz0, 0] + ry1 * g3[b01 + bz0, 1] + rz0 * g3[b01 + bz0, 2];
|
||||
v = rx1 * g3[b11 + bz0, 0] + ry1 * g3[b11 + bz0, 1] + rz0 * g3[b11 + bz0, 2];
|
||||
b = Utils.Lerp(u, v, t);
|
||||
|
||||
c = Utils.Lerp(a, b, sy);
|
||||
|
||||
u = rx0 * g3[b00 + bz1, 0] + ry0 * g3[b00 + bz1, 1] + rz1 * g3[b00 + bz1, 2];
|
||||
v = rx1 * g3[b10 + bz1, 0] + ry0 * g3[b10 + bz1, 1] + rz1 * g3[b10 + bz1, 2];
|
||||
a = Utils.Lerp(u, v, t);
|
||||
|
||||
u = rx0 * g3[b01 + bz1, 0] + ry1 * g3[b01 + bz1, 1] + rz1 * g3[b01 + bz1, 2];
|
||||
v = rx1 * g3[b11 + bz1, 0] + ry1 * g3[b11 + bz1, 1] + rz1 * g3[b11 + bz1, 2];
|
||||
b = Utils.Lerp(u, v, t);
|
||||
|
||||
d = Utils.Lerp(a, b, sy);
|
||||
return Utils.Lerp(c, d, sz);
|
||||
}
|
||||
|
||||
public static float turbulence1(float x, float freq)
|
||||
{
|
||||
float t;
|
||||
float v;
|
||||
|
||||
for (t = 0f; freq >= 1f; freq *= 0.5f)
|
||||
{
|
||||
v = freq * x;
|
||||
t += noise1(v) / freq;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
public static float turbulence2(float x, float y, float freq)
|
||||
{
|
||||
float t;
|
||||
Vector2 vec;
|
||||
|
||||
for (t = 0f; freq >= 1f; freq *= 0.5f)
|
||||
{
|
||||
vec.X = freq * x;
|
||||
vec.Y = freq * y;
|
||||
t += noise2(vec.X, vec.Y) / freq;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
public static float turbulence3(float x, float y, float z, float freq)
|
||||
{
|
||||
float t;
|
||||
Vector3 vec;
|
||||
|
||||
for (t = 0f; freq >= 1f; freq *= 0.5f)
|
||||
{
|
||||
vec.X = freq * x;
|
||||
vec.Y = freq * y;
|
||||
vec.Z = freq * z;
|
||||
t += noise3(vec.X, vec.Y, vec.Z) / freq;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
private static void normalize2(float[,] v, int i)
|
||||
{
|
||||
float s;
|
||||
|
||||
s = (float)Math.Sqrt(v[i, 0] * v[i, 0] + v[i, 1] * v[i, 1]);
|
||||
s = 1.0f / s;
|
||||
v[i, 0] = v[i, 0] * s;
|
||||
v[i, 1] = v[i, 1] * s;
|
||||
}
|
||||
|
||||
private static void normalize3(float[,] v, int i)
|
||||
{
|
||||
float s;
|
||||
|
||||
s = (float)Math.Sqrt(v[i, 0] * v[i, 0] + v[i, 1] * v[i, 1] + v[i, 2] * v[i, 2]);
|
||||
s = 1.0f / s;
|
||||
|
||||
v[i, 0] = v[i, 0] * s;
|
||||
v[i, 1] = v[i, 1] * s;
|
||||
v[i, 2] = v[i, 2] * s;
|
||||
}
|
||||
|
||||
private static float s_curve(float t)
|
||||
{
|
||||
return t * t * (3f - 2f * t);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,388 @@
|
|||
/*
|
||||
* Copyright (c) Contributors, http://opensimulator.org/
|
||||
* See CONTRIBUTORS.TXT for a full list of copyright holders.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of the OpenSimulator Project nor the
|
||||
* names of its contributors may be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
|
||||
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using log4net;
|
||||
using OpenMetaverse;
|
||||
using OpenSim.Framework;
|
||||
using OpenSim.Region.Framework.Interfaces;
|
||||
using OpenSim.Services.Interfaces;
|
||||
|
||||
namespace OpenSim.Region.CoreModules.World.Warp3DMap
|
||||
{
|
||||
public static class TerrainSplat
|
||||
{
|
||||
#region Constants
|
||||
|
||||
private static readonly UUID DIRT_DETAIL = new UUID("0bc58228-74a0-7e83-89bc-5c23464bcec5");
|
||||
private static readonly UUID GRASS_DETAIL = new UUID("63338ede-0037-c4fd-855b-015d77112fc8");
|
||||
private static readonly UUID MOUNTAIN_DETAIL = new UUID("303cd381-8560-7579-23f1-f0a880799740");
|
||||
private static readonly UUID ROCK_DETAIL = new UUID("53a2f406-4895-1d13-d541-d2e3b86bc19c");
|
||||
|
||||
private static readonly UUID[] DEFAULT_TERRAIN_DETAIL = new UUID[]
|
||||
{
|
||||
DIRT_DETAIL,
|
||||
GRASS_DETAIL,
|
||||
MOUNTAIN_DETAIL,
|
||||
ROCK_DETAIL
|
||||
};
|
||||
|
||||
private static readonly Color[] DEFAULT_TERRAIN_COLOR = new Color[]
|
||||
{
|
||||
Color.FromArgb(255, 164, 136, 117),
|
||||
Color.FromArgb(255, 65, 87, 47),
|
||||
Color.FromArgb(255, 157, 145, 131),
|
||||
Color.FromArgb(255, 125, 128, 130)
|
||||
};
|
||||
|
||||
private static readonly UUID TERRAIN_CACHE_MAGIC = new UUID("2c0c7ef2-56be-4eb8-aacb-76712c535b4b");
|
||||
|
||||
#endregion Constants
|
||||
|
||||
private static readonly ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name);
|
||||
private static string LogHeader = "[WARP3D TERRAIN SPLAT]";
|
||||
|
||||
/// <summary>
|
||||
/// Builds a composited terrain texture given the region texture
|
||||
/// and heightmap settings
|
||||
/// </summary>
|
||||
/// <param name="terrain">Terrain heightmap</param>
|
||||
/// <param name="regionInfo">Region information including terrain texture parameters</param>
|
||||
/// <returns>A 256x256 square RGB texture ready for rendering</returns>
|
||||
/// <remarks>Based on the algorithm described at http://opensimulator.org/wiki/Terrain_Splatting
|
||||
/// Note we create a 256x256 dimension texture even if the actual terrain is larger.
|
||||
/// </remarks>
|
||||
|
||||
public static Bitmap Splat(ITerrainChannel terrain,
|
||||
UUID[] textureIDs, float[] startHeights, float[] heightRanges,
|
||||
Vector3d regionPosition, IAssetService assetService, bool textureTerrain)
|
||||
{
|
||||
Debug.Assert(textureIDs.Length == 4);
|
||||
Debug.Assert(startHeights.Length == 4);
|
||||
Debug.Assert(heightRanges.Length == 4);
|
||||
|
||||
Bitmap[] detailTexture = new Bitmap[4];
|
||||
|
||||
if (textureTerrain)
|
||||
{
|
||||
// Swap empty terrain textureIDs with default IDs
|
||||
for (int i = 0; i < textureIDs.Length; i++)
|
||||
{
|
||||
if (textureIDs[i] == UUID.Zero)
|
||||
textureIDs[i] = DEFAULT_TERRAIN_DETAIL[i];
|
||||
}
|
||||
|
||||
#region Texture Fetching
|
||||
|
||||
if (assetService != null)
|
||||
{
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
AssetBase asset;
|
||||
UUID cacheID = UUID.Combine(TERRAIN_CACHE_MAGIC, textureIDs[i]);
|
||||
|
||||
// Try to fetch a cached copy of the decoded/resized version of this texture
|
||||
asset = assetService.GetCached(cacheID.ToString());
|
||||
if (asset != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (System.IO.MemoryStream stream = new System.IO.MemoryStream(asset.Data))
|
||||
detailTexture[i] = (Bitmap)Image.FromStream(stream);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
m_log.Warn("Failed to decode cached terrain texture " + cacheID +
|
||||
" (textureID: " + textureIDs[i] + "): " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
if (detailTexture[i] == null)
|
||||
{
|
||||
// Try to fetch the original JPEG2000 texture, resize if needed, and cache as PNG
|
||||
asset = assetService.Get(textureIDs[i].ToString());
|
||||
if (asset != null)
|
||||
{
|
||||
// m_log.DebugFormat(
|
||||
// "[TERRAIN SPLAT]: Got cached original JPEG2000 terrain texture {0} {1}", i, asset.ID);
|
||||
|
||||
try { detailTexture[i] = (Bitmap)CSJ2K.J2kImage.FromBytes(asset.Data); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
m_log.Warn("Failed to decode terrain texture " + asset.ID + ": " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
if (detailTexture[i] != null)
|
||||
{
|
||||
// Make sure this texture is the correct size, otherwise resize
|
||||
if (detailTexture[i].Width != 256 || detailTexture[i].Height != 256)
|
||||
{
|
||||
using (Bitmap origBitmap = detailTexture[i])
|
||||
{
|
||||
detailTexture[i] = ImageUtils.ResizeImage(origBitmap, 256, 256);
|
||||
}
|
||||
}
|
||||
|
||||
// Save the decoded and resized texture to the cache
|
||||
byte[] data;
|
||||
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
|
||||
{
|
||||
detailTexture[i].Save(stream, ImageFormat.Png);
|
||||
data = stream.ToArray();
|
||||
}
|
||||
|
||||
// Cache a PNG copy of this terrain texture
|
||||
AssetBase newAsset = new AssetBase
|
||||
{
|
||||
Data = data,
|
||||
Description = "PNG",
|
||||
Flags = AssetFlags.Collectable,
|
||||
FullID = cacheID,
|
||||
ID = cacheID.ToString(),
|
||||
Local = true,
|
||||
Name = String.Empty,
|
||||
Temporary = true,
|
||||
Type = (sbyte)AssetType.Unknown
|
||||
};
|
||||
newAsset.Metadata.ContentType = "image/png";
|
||||
assetService.Store(newAsset);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion Texture Fetching
|
||||
}
|
||||
|
||||
// Fill in any missing textures with a solid color
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
if (detailTexture[i] == null)
|
||||
{
|
||||
m_log.DebugFormat("{0} Missing terrain texture for layer {1}. Filling with solid default color",
|
||||
LogHeader, i);
|
||||
// Create a solid color texture for this layer
|
||||
detailTexture[i] = new Bitmap(256, 256, PixelFormat.Format24bppRgb);
|
||||
using (Graphics gfx = Graphics.FromImage(detailTexture[i]))
|
||||
{
|
||||
using (SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR[i]))
|
||||
gfx.FillRectangle(brush, 0, 0, 256, 256);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (detailTexture[i].Width != 256 || detailTexture[i].Height != 256)
|
||||
{
|
||||
detailTexture[i] = ResizeBitmap(detailTexture[i], 256, 256);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#region Layer Map
|
||||
|
||||
float[,] layermap = new float[256, 256];
|
||||
|
||||
// Scale difference between actual region size and the 256 texture being created
|
||||
int xFactor = terrain.Width / 256;
|
||||
int yFactor = terrain.Height / 256;
|
||||
|
||||
// Create 'layermap' where each value is the fractional layer number to place
|
||||
// at that point. For instance, a value of 1.345 gives the blending of
|
||||
// layer 1 and layer 2 for that point.
|
||||
for (int y = 0; y < 256; y++)
|
||||
{
|
||||
for (int x = 0; x < 256; x++)
|
||||
{
|
||||
float height = (float)terrain[x * xFactor, y * yFactor];
|
||||
|
||||
float pctX = (float)x / 255f;
|
||||
float pctY = (float)y / 255f;
|
||||
|
||||
// Use bilinear interpolation between the four corners of start height and
|
||||
// height range to select the current values at this position
|
||||
float startHeight = ImageUtils.Bilinear(
|
||||
startHeights[0],
|
||||
startHeights[2],
|
||||
startHeights[1],
|
||||
startHeights[3],
|
||||
pctX, pctY);
|
||||
startHeight = Utils.Clamp(startHeight, 0f, 255f);
|
||||
|
||||
float heightRange = ImageUtils.Bilinear(
|
||||
heightRanges[0],
|
||||
heightRanges[2],
|
||||
heightRanges[1],
|
||||
heightRanges[3],
|
||||
pctX, pctY);
|
||||
heightRange = Utils.Clamp(heightRange, 0f, 255f);
|
||||
|
||||
// Generate two frequencies of perlin noise based on our global position
|
||||
// The magic values were taken from http://opensimulator.org/wiki/Terrain_Splatting
|
||||
Vector3 vec = new Vector3
|
||||
(
|
||||
((float)regionPosition.X + (x * xFactor)) * 0.20319f,
|
||||
((float)regionPosition.Y + (y * yFactor)) * 0.20319f,
|
||||
height * 0.25f
|
||||
);
|
||||
|
||||
float lowFreq = Perlin.noise2(vec.X * 0.222222f, vec.Y * 0.222222f) * 6.5f;
|
||||
float highFreq = Perlin.turbulence2(vec.X, vec.Y, 2f) * 2.25f;
|
||||
float noise = (lowFreq + highFreq) * 2f;
|
||||
|
||||
// Combine the current height, generated noise, start height, and height range parameters, then scale all of it
|
||||
float layer = ((height + noise - startHeight) / heightRange) * 4f;
|
||||
if (Single.IsNaN(layer))
|
||||
layer = 0f;
|
||||
layermap[x, y] = Utils.Clamp(layer, 0f, 3f);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion Layer Map
|
||||
|
||||
#region Texture Compositing
|
||||
|
||||
Bitmap output = new Bitmap(256, 256, PixelFormat.Format24bppRgb);
|
||||
BitmapData outputData = output.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
|
||||
|
||||
// Unsafe work as we lock down the source textures for quicker access and access the
|
||||
// pixel data directly
|
||||
unsafe
|
||||
{
|
||||
// Get handles to all of the texture data arrays
|
||||
BitmapData[] datas = new BitmapData[]
|
||||
{
|
||||
detailTexture[0].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[0].PixelFormat),
|
||||
detailTexture[1].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[1].PixelFormat),
|
||||
detailTexture[2].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[2].PixelFormat),
|
||||
detailTexture[3].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[3].PixelFormat)
|
||||
};
|
||||
|
||||
// Compute size of each pixel data (used to address into the pixel data array)
|
||||
int[] comps = new int[]
|
||||
{
|
||||
(datas[0].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
|
||||
(datas[1].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
|
||||
(datas[2].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
|
||||
(datas[3].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3
|
||||
};
|
||||
|
||||
for (int y = 0; y < 256; y++)
|
||||
{
|
||||
for (int x = 0; x < 256; x++)
|
||||
{
|
||||
float layer = layermap[x, y];
|
||||
|
||||
// Select two textures
|
||||
int l0 = (int)Math.Floor(layer);
|
||||
int l1 = Math.Min(l0 + 1, 3);
|
||||
|
||||
byte* ptrA = (byte*)datas[l0].Scan0 + y * datas[l0].Stride + x * comps[l0];
|
||||
byte* ptrB = (byte*)datas[l1].Scan0 + y * datas[l1].Stride + x * comps[l1];
|
||||
byte* ptrO = (byte*)outputData.Scan0 + y * outputData.Stride + x * 3;
|
||||
|
||||
float aB = *(ptrA + 0);
|
||||
float aG = *(ptrA + 1);
|
||||
float aR = *(ptrA + 2);
|
||||
|
||||
float bB = *(ptrB + 0);
|
||||
float bG = *(ptrB + 1);
|
||||
float bR = *(ptrB + 2);
|
||||
|
||||
float layerDiff = layer - l0;
|
||||
|
||||
// Interpolate between the two selected textures
|
||||
*(ptrO + 0) = (byte)Math.Floor(aB + layerDiff * (bB - aB));
|
||||
*(ptrO + 1) = (byte)Math.Floor(aG + layerDiff * (bG - aG));
|
||||
*(ptrO + 2) = (byte)Math.Floor(aR + layerDiff * (bR - aR));
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < detailTexture.Length; i++)
|
||||
detailTexture[i].UnlockBits(datas[i]);
|
||||
}
|
||||
|
||||
for (int i = 0; i < detailTexture.Length; i++)
|
||||
if (detailTexture[i] != null)
|
||||
detailTexture[i].Dispose();
|
||||
|
||||
output.UnlockBits(outputData);
|
||||
|
||||
// We generated the texture upside down, so flip it
|
||||
output.RotateFlip(RotateFlipType.RotateNoneFlipY);
|
||||
|
||||
#endregion Texture Compositing
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
public static Bitmap ResizeBitmap(Bitmap b, int nWidth, int nHeight)
|
||||
{
|
||||
m_log.DebugFormat("{0} ResizeBitmap. From <{1},{2}> to <{3},{4}>",
|
||||
LogHeader, b.Width, b.Height, nWidth, nHeight);
|
||||
Bitmap result = new Bitmap(nWidth, nHeight);
|
||||
using (Graphics g = Graphics.FromImage(result))
|
||||
g.DrawImage(b, 0, 0, nWidth, nHeight);
|
||||
b.Dispose();
|
||||
return result;
|
||||
}
|
||||
public static Bitmap SplatSimple(float[] heightmap)
|
||||
{
|
||||
const float BASE_HSV_H = 93f / 360f;
|
||||
const float BASE_HSV_S = 44f / 100f;
|
||||
const float BASE_HSV_V = 34f / 100f;
|
||||
|
||||
Bitmap img = new Bitmap(256, 256);
|
||||
BitmapData bitmapData = img.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
|
||||
|
||||
unsafe
|
||||
{
|
||||
for (int y = 255; y >= 0; y--)
|
||||
{
|
||||
for (int x = 0; x < 256; x++)
|
||||
{
|
||||
float normHeight = heightmap[y * 256 + x] / 255f;
|
||||
normHeight = Utils.Clamp(normHeight, BASE_HSV_V, 1.0f);
|
||||
|
||||
Color4 color = Color4.FromHSV(BASE_HSV_H, BASE_HSV_S, normHeight);
|
||||
|
||||
byte* ptr = (byte*)bitmapData.Scan0 + y * bitmapData.Stride + x * 3;
|
||||
*(ptr + 0) = (byte)(color.B * 255f);
|
||||
*(ptr + 1) = (byte)(color.G * 255f);
|
||||
*(ptr + 2) = (byte)(color.R * 255f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
img.UnlockBits(bitmapData);
|
||||
return img;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,165 @@
|
|||
/*
|
||||
* Copyright (c) Contributors, http://opensimulator.org/
|
||||
* See CONTRIBUTORS.TXT for a full list of copyright holders.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of the OpenSimulator Project nor the
|
||||
* names of its contributors may be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
|
||||
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using OpenMetaverse;
|
||||
|
||||
namespace OpenSim.Region.CoreModules.World.Warp3DMap
|
||||
{
|
||||
public class Viewport
|
||||
{
|
||||
private const float DEG_TO_RAD = (float)Math.PI / 180f;
|
||||
private static readonly Vector3 UP_DIRECTION = Vector3.UnitZ;
|
||||
|
||||
public Vector3 Position;
|
||||
public Vector3 LookDirection;
|
||||
public float FieldOfView;
|
||||
public float NearPlaneDistance;
|
||||
public float FarPlaneDistance;
|
||||
public int Width;
|
||||
public int Height;
|
||||
public bool Orthographic;
|
||||
public float OrthoWindowWidth;
|
||||
public float OrthoWindowHeight;
|
||||
|
||||
public Viewport(Vector3 position, Vector3 lookDirection, float fieldOfView, float farPlaneDist, float nearPlaneDist, int width, int height)
|
||||
{
|
||||
// Perspective projection mode
|
||||
Position = position;
|
||||
LookDirection = lookDirection;
|
||||
FieldOfView = fieldOfView;
|
||||
FarPlaneDistance = farPlaneDist;
|
||||
NearPlaneDistance = nearPlaneDist;
|
||||
Width = width;
|
||||
Height = height;
|
||||
}
|
||||
|
||||
public Viewport(Vector3 position, Vector3 lookDirection, float farPlaneDist, float nearPlaneDist, int width, int height, float orthoWindowWidth, float orthoWindowHeight)
|
||||
{
|
||||
// Orthographic projection mode
|
||||
Position = position;
|
||||
LookDirection = lookDirection;
|
||||
FarPlaneDistance = farPlaneDist;
|
||||
NearPlaneDistance = nearPlaneDist;
|
||||
Width = width;
|
||||
Height = height;
|
||||
OrthoWindowWidth = orthoWindowWidth;
|
||||
OrthoWindowHeight = orthoWindowHeight;
|
||||
Orthographic = true;
|
||||
}
|
||||
|
||||
public Point VectorToScreen(Vector3 v)
|
||||
{
|
||||
Matrix4 m = GetWorldToViewportMatrix();
|
||||
Vector3 screenPoint = v * m;
|
||||
return new Point((int)screenPoint.X, (int)screenPoint.Y);
|
||||
}
|
||||
|
||||
public Matrix4 GetWorldToViewportMatrix()
|
||||
{
|
||||
Matrix4 result = GetViewMatrix();
|
||||
result *= GetPerspectiveProjectionMatrix();
|
||||
result *= GetViewportMatrix();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public Matrix4 GetViewMatrix()
|
||||
{
|
||||
Vector3 zAxis = -LookDirection;
|
||||
zAxis.Normalize();
|
||||
|
||||
Vector3 xAxis = Vector3.Cross(UP_DIRECTION, zAxis);
|
||||
xAxis.Normalize();
|
||||
|
||||
Vector3 yAxis = Vector3.Cross(zAxis, xAxis);
|
||||
|
||||
Vector3 position = Position;
|
||||
float offsetX = -Vector3.Dot(xAxis, position);
|
||||
float offsetY = -Vector3.Dot(yAxis, position);
|
||||
float offsetZ = -Vector3.Dot(zAxis, position);
|
||||
|
||||
return new Matrix4(
|
||||
xAxis.X, yAxis.X, zAxis.X, 0f,
|
||||
xAxis.Y, yAxis.Y, zAxis.Y, 0f,
|
||||
xAxis.Z, yAxis.Z, zAxis.Z, 0f,
|
||||
offsetX, offsetY, offsetZ, 1f);
|
||||
}
|
||||
|
||||
public Matrix4 GetPerspectiveProjectionMatrix()
|
||||
{
|
||||
float aspectRatio = (float)Width / (float)Height;
|
||||
|
||||
float hFoV = FieldOfView * DEG_TO_RAD;
|
||||
float zn = NearPlaneDistance;
|
||||
float zf = FarPlaneDistance;
|
||||
|
||||
float xScale = 1f / (float)Math.Tan(hFoV / 2f);
|
||||
float yScale = aspectRatio * xScale;
|
||||
float m33 = (zf == double.PositiveInfinity) ? -1 : (zf / (zn - zf));
|
||||
float m43 = zn * m33;
|
||||
|
||||
return new Matrix4(
|
||||
xScale, 0f, 0f, 0f,
|
||||
0f, yScale, 0f, 0f,
|
||||
0f, 0f, m33, -1f,
|
||||
0f, 0f, m43, 0f);
|
||||
}
|
||||
|
||||
public Matrix4 GetOrthographicProjectionMatrix(float aspectRatio)
|
||||
{
|
||||
float w = Width;
|
||||
float h = Height;
|
||||
float zn = NearPlaneDistance;
|
||||
float zf = FarPlaneDistance;
|
||||
|
||||
float m33 = 1 / (zn - zf);
|
||||
float m43 = zn * m33;
|
||||
|
||||
return new Matrix4(
|
||||
2f / w, 0f, 0f, 0f,
|
||||
0f, 2f / h, 0f, 0f,
|
||||
0f, 0f, m33, 0f,
|
||||
0f, 0f, m43, 1f);
|
||||
}
|
||||
|
||||
public Matrix4 GetViewportMatrix()
|
||||
{
|
||||
float scaleX = (float)Width * 0.5f;
|
||||
float scaleY = (float)Height * 0.5f;
|
||||
float offsetX = 0f + scaleX;
|
||||
float offsetY = 0f + scaleY;
|
||||
|
||||
return new Matrix4(
|
||||
scaleX, 0f, 0f, 0f,
|
||||
0f, -scaleY, 0f, 0f,
|
||||
0f, 0f, 1f, 0f,
|
||||
offsetX, offsetY, 0f, 1f);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,833 @@
|
|||
/*
|
||||
* Copyright (c) Contributors, http://opensimulator.org/
|
||||
* See CONTRIBUTORS.TXT for a full list of copyright holders.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of the OpenSimulator Project nor the
|
||||
* names of its contributors may be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
|
||||
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
|
||||
using CSJ2K;
|
||||
using Nini.Config;
|
||||
using log4net;
|
||||
using Warp3D;
|
||||
using Mono.Addins;
|
||||
|
||||
using OpenSim.Framework;
|
||||
using OpenSim.Region.Framework.Interfaces;
|
||||
using OpenSim.Region.Framework.Scenes;
|
||||
using OpenSim.Region.PhysicsModules.SharedBase;
|
||||
using OpenSim.Services.Interfaces;
|
||||
|
||||
using OpenMetaverse;
|
||||
using OpenMetaverse.Assets;
|
||||
using OpenMetaverse.Imaging;
|
||||
using OpenMetaverse.Rendering;
|
||||
using OpenMetaverse.StructuredData;
|
||||
|
||||
using WarpRenderer = global::Warp3D.Warp3D;
|
||||
using System.Drawing.Drawing2D;
|
||||
|
||||
[assembly: Addin("Warp3DCachedImageModule", "1.0")]
|
||||
[assembly: AddinDependency("OpenSim.Region.Framework", OpenSim.VersionInfo.VersionNumber)]
|
||||
namespace OpenSim.Region.CoreModules.World.Warp3DMap
|
||||
{
|
||||
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "Warp3DCachedImageModule")]
|
||||
public class Warp3DImageModule : IMapImageGenerator, INonSharedRegionModule
|
||||
{
|
||||
private static readonly UUID TEXTURE_METADATA_MAGIC = new UUID("802dc0e0-f080-4931-8b57-d1be8611c4f3");
|
||||
private static readonly Color4 WATER_COLOR = new Color4(29, 72, 96, 216);
|
||||
|
||||
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
|
||||
|
||||
#pragma warning disable 414
|
||||
private static string LogHeader = "[CACHED WARP 3D IMAGE MODULE]";
|
||||
#pragma warning restore 414
|
||||
|
||||
private Scene m_scene;
|
||||
private IRendering m_primMesher;
|
||||
private Dictionary<UUID, Color4> m_colors = new Dictionary<UUID, Color4>();
|
||||
|
||||
private IConfigSource m_config;
|
||||
private bool m_drawPrimVolume = true; // true if should render the prims on the tile
|
||||
private bool m_textureTerrain = true; // true if to create terrain splatting texture
|
||||
private bool m_texturePrims = true; // true if should texture the rendered prims
|
||||
private float m_texturePrimSize = 48f; // size of prim before we consider texturing it
|
||||
private bool m_renderMeshes = false; // true if to render meshes rather than just bounding boxes
|
||||
private String m_cacheDirectory = "";
|
||||
private bool m_Enabled = false;
|
||||
|
||||
// private Bitmap lastImage = null;
|
||||
private DateTime lastImageTime = DateTime.MinValue;
|
||||
|
||||
#region Region Module interface
|
||||
|
||||
public void Initialise(IConfigSource source)
|
||||
{
|
||||
m_config = source;
|
||||
|
||||
string[] configSections = new string[] { "Map", "Startup" };
|
||||
|
||||
if (Util.GetConfigVarFromSections<string>(
|
||||
m_config, "MapImageModule", configSections, "MapImageModule") != "Warp3DCachedImageModule")
|
||||
return;
|
||||
|
||||
m_Enabled = true;
|
||||
|
||||
m_drawPrimVolume
|
||||
= Util.GetConfigVarFromSections<bool>(m_config, "DrawPrimOnMapTile", configSections, m_drawPrimVolume);
|
||||
m_textureTerrain
|
||||
= Util.GetConfigVarFromSections<bool>(m_config, "TextureOnMapTile", configSections, m_textureTerrain);
|
||||
m_texturePrims
|
||||
= Util.GetConfigVarFromSections<bool>(m_config, "TexturePrims", configSections, m_texturePrims);
|
||||
m_texturePrimSize
|
||||
= Util.GetConfigVarFromSections<float>(m_config, "TexturePrimSize", configSections, m_texturePrimSize);
|
||||
m_renderMeshes
|
||||
= Util.GetConfigVarFromSections<bool>(m_config, "RenderMeshes", configSections, m_renderMeshes);
|
||||
m_cacheDirectory
|
||||
= Util.GetConfigVarFromSections<string>(m_config, "CacheDirectory", configSections, System.IO.Path.Combine(new DirectoryInfo(".").FullName, "MapImageCache"));
|
||||
|
||||
if (!Directory.Exists(m_cacheDirectory))
|
||||
Directory.CreateDirectory(m_cacheDirectory);
|
||||
}
|
||||
|
||||
public void AddRegion(Scene scene)
|
||||
{
|
||||
if (!m_Enabled)
|
||||
return;
|
||||
|
||||
m_scene = scene;
|
||||
|
||||
List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
|
||||
if (renderers.Count > 0)
|
||||
m_log.Info("[MAPTILE]: Loaded prim mesher " + renderers[0]);
|
||||
else
|
||||
m_log.Info("[MAPTILE]: No prim mesher loaded, prim rendering will be disabled");
|
||||
|
||||
m_scene.RegisterModuleInterface<IMapImageGenerator>(this);
|
||||
}
|
||||
|
||||
public void RegionLoaded(Scene scene)
|
||||
{
|
||||
}
|
||||
|
||||
public void RemoveRegion(Scene scene)
|
||||
{
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
}
|
||||
|
||||
public string Name
|
||||
{
|
||||
get { return "Warp3DImageModule"; }
|
||||
}
|
||||
|
||||
public Type ReplaceableInterface
|
||||
{
|
||||
get { return null; }
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IMapImageGenerator Members
|
||||
public static int getCurrentUnixTime()
|
||||
{
|
||||
return (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
|
||||
}
|
||||
|
||||
public static String unixTimeToDateString(int unixTime)
|
||||
{
|
||||
DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
|
||||
long unixTimeStampInTicks = (long)(unixTime * TimeSpan.TicksPerSecond);
|
||||
DateTime _date = new DateTime(unixStart.Ticks + unixTimeStampInTicks, System.DateTimeKind.Utc);
|
||||
|
||||
return _date.Day + "." + _date.Month + "." + _date.Year + " " + _date.Hour + ":" + _date.Minute;
|
||||
}
|
||||
|
||||
private void writeDateOnMap(ref Bitmap _map)
|
||||
{
|
||||
RectangleF rectf = new RectangleF(5, 5, 200, 25);
|
||||
|
||||
Graphics g = Graphics.FromImage(_map);
|
||||
g.SmoothingMode = SmoothingMode.AntiAlias;
|
||||
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
|
||||
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
|
||||
g.DrawString(unixTimeToDateString(getCurrentUnixTime()), new Font("Arial", 8), Brushes.Black, rectf);
|
||||
g.Flush();
|
||||
}
|
||||
|
||||
public Bitmap CreateMapTile()
|
||||
{
|
||||
if(File.Exists(System.IO.Path.Combine(m_cacheDirectory, m_scene.RegionInfo.RegionID + ".bmp")))
|
||||
{
|
||||
return new Bitmap(System.IO.Path.Combine(m_cacheDirectory, m_scene.RegionInfo.RegionID + ".bmp"));
|
||||
}
|
||||
else
|
||||
{
|
||||
/* this must be on all map, not just its image
|
||||
if ((DateTime.Now - lastImageTime).TotalSeconds < 3600)
|
||||
{
|
||||
return (Bitmap)lastImage.Clone();
|
||||
}
|
||||
*/
|
||||
|
||||
List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
|
||||
if (renderers.Count > 0)
|
||||
{
|
||||
m_primMesher = RenderingLoader.LoadRenderer(renderers[0]);
|
||||
}
|
||||
|
||||
Vector3 camPos = new Vector3(
|
||||
m_scene.RegionInfo.RegionSizeX / 2 - 0.5f,
|
||||
m_scene.RegionInfo.RegionSizeY / 2 - 0.5f,
|
||||
221.7025033688163f);
|
||||
// Viewport viewing down onto the region
|
||||
Viewport viewport = new Viewport(camPos, -Vector3.UnitZ, 1024f, 0.1f,
|
||||
(int)m_scene.RegionInfo.RegionSizeX, (int)m_scene.RegionInfo.RegionSizeY,
|
||||
(float)m_scene.RegionInfo.RegionSizeX, (float)m_scene.RegionInfo.RegionSizeY);
|
||||
|
||||
Bitmap tile = CreateMapTile(viewport, false);
|
||||
writeDateOnMap(ref tile);
|
||||
tile.Save(System.IO.Path.Combine(m_cacheDirectory, m_scene.RegionInfo.RegionID + ".bmp"));
|
||||
m_primMesher = null;
|
||||
return tile;
|
||||
/*
|
||||
lastImage = tile;
|
||||
lastImageTime = DateTime.Now;
|
||||
return (Bitmap)lastImage.Clone();
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
||||
public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float fov, int width, int height, bool useTextures)
|
||||
{
|
||||
Viewport viewport = new Viewport(camPos, camDir, fov, Constants.RegionSize, 0.1f, width, height);
|
||||
return CreateMapTile(viewport, useTextures);
|
||||
}
|
||||
|
||||
public Bitmap CreateMapTile(Viewport viewport, bool useTextures)
|
||||
{
|
||||
m_colors.Clear();
|
||||
|
||||
int width = viewport.Width;
|
||||
int height = viewport.Height;
|
||||
|
||||
WarpRenderer renderer = new WarpRenderer();
|
||||
|
||||
if(!renderer.CreateScene(width, height))
|
||||
return new Bitmap(width,height);
|
||||
|
||||
#region Camera
|
||||
|
||||
warp_Vector pos = ConvertVector(viewport.Position);
|
||||
warp_Vector lookat = warp_Vector.add(ConvertVector(viewport.Position), ConvertVector(viewport.LookDirection));
|
||||
|
||||
renderer.Scene.defaultCamera.setPos(pos);
|
||||
renderer.Scene.defaultCamera.lookAt(lookat);
|
||||
|
||||
if (viewport.Orthographic)
|
||||
{
|
||||
renderer.Scene.defaultCamera.setOrthographic(true,viewport.OrthoWindowWidth, viewport.OrthoWindowHeight);
|
||||
}
|
||||
else
|
||||
{
|
||||
float fov = viewport.FieldOfView;
|
||||
fov *= 1.75f; // FIXME: ???
|
||||
renderer.Scene.defaultCamera.setFov(fov);
|
||||
}
|
||||
|
||||
#endregion Camera
|
||||
|
||||
renderer.Scene.addLight("Light1", new warp_Light(new warp_Vector(1.0f, 0.5f, 1f), 0xffffff, 0, 320, 40));
|
||||
renderer.Scene.addLight("Light2", new warp_Light(new warp_Vector(-1f, -1f, 1f), 0xffffff, 0, 100, 40));
|
||||
|
||||
CreateWater(renderer);
|
||||
CreateTerrain(renderer, m_textureTerrain);
|
||||
if (m_drawPrimVolume)
|
||||
CreateAllPrims(renderer, useTextures);
|
||||
|
||||
renderer.Render();
|
||||
Bitmap bitmap = renderer.Scene.getImage();
|
||||
|
||||
renderer.Scene.destroy();
|
||||
renderer.Reset();
|
||||
renderer = null;
|
||||
viewport = null;
|
||||
|
||||
m_colors.Clear();
|
||||
GC.Collect();
|
||||
m_log.Debug("[WARP 3D IMAGE MODULE]: GC.Collect()");
|
||||
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
public byte[] WriteJpeg2000Image()
|
||||
{
|
||||
try
|
||||
{
|
||||
using (Bitmap mapbmp = CreateMapTile())
|
||||
return OpenJPEG.EncodeFromImage(mapbmp, true);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// JPEG2000 encoder failed
|
||||
m_log.Error("[WARP 3D IMAGE MODULE]: Failed generating terrain map: ", e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Rendering Methods
|
||||
|
||||
// Add a water plane to the renderer.
|
||||
private void CreateWater(WarpRenderer renderer)
|
||||
{
|
||||
float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
|
||||
|
||||
renderer.AddPlane("Water", m_scene.RegionInfo.RegionSizeX * 0.5f);
|
||||
renderer.Scene.sceneobject("Water").setPos(m_scene.RegionInfo.RegionSizeX * 0.5f - 0.5f,
|
||||
waterHeight,
|
||||
m_scene.RegionInfo.RegionSizeY * 0.5f - 0.5f);
|
||||
|
||||
warp_Material waterColorMaterial = new warp_Material(ConvertColor(WATER_COLOR));
|
||||
waterColorMaterial.setReflectivity(0); // match water color with standard map module thanks lkalif
|
||||
waterColorMaterial.setTransparency((byte)((1f - WATER_COLOR.A) * 255f));
|
||||
renderer.Scene.addMaterial("WaterColor", waterColorMaterial);
|
||||
renderer.SetObjectMaterial("Water", "WaterColor");
|
||||
}
|
||||
|
||||
// Add a terrain to the renderer.
|
||||
// Note that we create a 'low resolution' 256x256 vertex terrain rather than trying for
|
||||
// full resolution. This saves a lot of memory especially for very large regions.
|
||||
private void CreateTerrain(WarpRenderer renderer, bool textureTerrain)
|
||||
{
|
||||
ITerrainChannel terrain = m_scene.Heightmap;
|
||||
|
||||
float regionsx = m_scene.RegionInfo.RegionSizeX;
|
||||
float regionsy = m_scene.RegionInfo.RegionSizeY;
|
||||
|
||||
// 'diff' is the difference in scale between the real region size and the size of terrain we're buiding
|
||||
float diff = regionsx / 256f;
|
||||
|
||||
int npointsx =(int)(regionsx / diff);
|
||||
int npointsy =(int)(regionsy / diff);
|
||||
|
||||
float invsx = 1.0f / regionsx;
|
||||
float invsy = 1.0f / (float)m_scene.RegionInfo.RegionSizeY;
|
||||
|
||||
// Create all the vertices for the terrain
|
||||
warp_Object obj = new warp_Object();
|
||||
for (float y = 0; y < regionsy; y += diff)
|
||||
{
|
||||
for (float x = 0; x < regionsx; x += diff)
|
||||
{
|
||||
warp_Vector pos = ConvertVector(x , y , (float)terrain[(int)x, (int)y]);
|
||||
obj.addVertex(new warp_Vertex(pos, x * invsx, 1.0f - y * invsy));
|
||||
}
|
||||
}
|
||||
|
||||
// Now that we have all the vertices, make another pass and
|
||||
// create the list of triangle indices.
|
||||
float invdiff = 1.0f / diff;
|
||||
int limx = npointsx - 1;
|
||||
int limy = npointsy - 1;
|
||||
for (float y = 0; y < regionsy; y += diff)
|
||||
{
|
||||
for (float x = 0; x < regionsx; x += diff)
|
||||
{
|
||||
float newX = x * invdiff;
|
||||
float newY = y * invdiff;
|
||||
if (newX < limx && newY < limy)
|
||||
{
|
||||
int v = (int)newY * npointsx + (int)newX;
|
||||
|
||||
// Make two triangles for each of the squares in the grid of vertices
|
||||
obj.addTriangle(
|
||||
v,
|
||||
v + 1,
|
||||
v + npointsx);
|
||||
|
||||
obj.addTriangle(
|
||||
v + npointsx + 1,
|
||||
v + npointsx,
|
||||
v + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
renderer.Scene.addObject("Terrain", obj);
|
||||
|
||||
UUID[] textureIDs = new UUID[4];
|
||||
float[] startHeights = new float[4];
|
||||
float[] heightRanges = new float[4];
|
||||
|
||||
OpenSim.Framework.RegionSettings regionInfo = m_scene.RegionInfo.RegionSettings;
|
||||
|
||||
textureIDs[0] = regionInfo.TerrainTexture1;
|
||||
textureIDs[1] = regionInfo.TerrainTexture2;
|
||||
textureIDs[2] = regionInfo.TerrainTexture3;
|
||||
textureIDs[3] = regionInfo.TerrainTexture4;
|
||||
|
||||
startHeights[0] = (float)regionInfo.Elevation1SW;
|
||||
startHeights[1] = (float)regionInfo.Elevation1NW;
|
||||
startHeights[2] = (float)regionInfo.Elevation1SE;
|
||||
startHeights[3] = (float)regionInfo.Elevation1NE;
|
||||
|
||||
heightRanges[0] = (float)regionInfo.Elevation2SW;
|
||||
heightRanges[1] = (float)regionInfo.Elevation2NW;
|
||||
heightRanges[2] = (float)regionInfo.Elevation2SE;
|
||||
heightRanges[3] = (float)regionInfo.Elevation2NE;
|
||||
|
||||
uint globalX, globalY;
|
||||
Util.RegionHandleToWorldLoc(m_scene.RegionInfo.RegionHandle, out globalX, out globalY);
|
||||
|
||||
warp_Texture texture;
|
||||
using (Bitmap image = TerrainSplat.Splat(
|
||||
terrain, textureIDs, startHeights, heightRanges,
|
||||
new Vector3d(globalX, globalY, 0.0), m_scene.AssetService, textureTerrain))
|
||||
texture = new warp_Texture(image);
|
||||
|
||||
warp_Material material = new warp_Material(texture);
|
||||
material.setReflectivity(50);
|
||||
renderer.Scene.addMaterial("TerrainColor", material);
|
||||
renderer.Scene.material("TerrainColor").setReflectivity(0); // reduces tile seams a bit thanks lkalif
|
||||
renderer.SetObjectMaterial("Terrain", "TerrainColor");
|
||||
}
|
||||
|
||||
private void CreateAllPrims(WarpRenderer renderer, bool useTextures)
|
||||
{
|
||||
if (m_primMesher == null)
|
||||
return;
|
||||
|
||||
m_scene.ForEachSOG(
|
||||
delegate(SceneObjectGroup group)
|
||||
{
|
||||
foreach (SceneObjectPart child in group.Parts)
|
||||
CreatePrim(renderer, child, useTextures);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim,
|
||||
bool useTextures)
|
||||
{
|
||||
const float MIN_SIZE_SQUARE = 4f;
|
||||
|
||||
if ((PCode)prim.Shape.PCode != PCode.Prim)
|
||||
return;
|
||||
float primScaleLenSquared = prim.Scale.LengthSquared();
|
||||
|
||||
if (primScaleLenSquared < MIN_SIZE_SQUARE)
|
||||
return;
|
||||
|
||||
FacetedMesh renderMesh = null;
|
||||
Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);
|
||||
|
||||
if (m_renderMeshes)
|
||||
{
|
||||
if (omvPrim.Sculpt != null && omvPrim.Sculpt.SculptTexture != UUID.Zero)
|
||||
{
|
||||
// Try fetchinng the asset
|
||||
byte[] sculptAsset = m_scene.AssetService.GetData(omvPrim.Sculpt.SculptTexture.ToString());
|
||||
if (sculptAsset != null)
|
||||
{
|
||||
// Is it a mesh?
|
||||
if (omvPrim.Sculpt.Type == SculptType.Mesh)
|
||||
{
|
||||
AssetMesh meshAsset = new AssetMesh(omvPrim.Sculpt.SculptTexture, sculptAsset);
|
||||
FacetedMesh.TryDecodeFromAsset(omvPrim, meshAsset, DetailLevel.Highest, out renderMesh);
|
||||
meshAsset = null;
|
||||
}
|
||||
else // It's sculptie
|
||||
{
|
||||
IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>();
|
||||
if(imgDecoder != null)
|
||||
{
|
||||
Image sculpt = imgDecoder.DecodeToImage(sculptAsset);
|
||||
if(sculpt != null)
|
||||
{
|
||||
renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim,(Bitmap)sculpt,
|
||||
DetailLevel.Medium);
|
||||
sculpt.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If not a mesh or sculptie, try the regular mesher
|
||||
if (renderMesh == null)
|
||||
{
|
||||
renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
|
||||
}
|
||||
|
||||
if (renderMesh == null)
|
||||
return;
|
||||
|
||||
string primID = prim.UUID.ToString();
|
||||
|
||||
// Create the prim faces
|
||||
// TODO: Implement the useTextures flag behavior
|
||||
for (int i = 0; i < renderMesh.Faces.Count; i++)
|
||||
{
|
||||
Face face = renderMesh.Faces[i];
|
||||
string meshName = primID + i.ToString();
|
||||
|
||||
// Avoid adding duplicate meshes to the scene
|
||||
if (renderer.Scene.objectData.ContainsKey(meshName))
|
||||
continue;
|
||||
|
||||
warp_Object faceObj = new warp_Object();
|
||||
for (int j = 0; j < face.Vertices.Count; j++)
|
||||
{
|
||||
Vertex v = face.Vertices[j];
|
||||
warp_Vector pos = ConvertVector(v.Position);
|
||||
warp_Vertex vert = new warp_Vertex(pos, v.TexCoord.X, v.TexCoord.Y);
|
||||
faceObj.addVertex(vert);
|
||||
}
|
||||
|
||||
for (int j = 0; j < face.Indices.Count; j += 3)
|
||||
{
|
||||
faceObj.addTriangle(
|
||||
face.Indices[j + 0],
|
||||
face.Indices[j + 1],
|
||||
face.Indices[j + 2]);
|
||||
}
|
||||
|
||||
Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
|
||||
Color4 faceColor = GetFaceColor(teFace);
|
||||
string materialName = String.Empty;
|
||||
if (m_texturePrims && primScaleLenSquared > m_texturePrimSize*m_texturePrimSize)
|
||||
materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID);
|
||||
else
|
||||
materialName = GetOrCreateMaterial(renderer, faceColor);
|
||||
|
||||
warp_Vector primPos = ConvertVector(prim.GetWorldPosition());
|
||||
warp_Quaternion primRot = ConvertQuaternion(prim.GetWorldRotation());
|
||||
warp_Matrix m = warp_Matrix.quaternionMatrix(primRot);
|
||||
faceObj.transform(m);
|
||||
faceObj.setPos(primPos);
|
||||
faceObj.scaleSelf(prim.Scale.X, prim.Scale.Z, prim.Scale.Y);
|
||||
|
||||
renderer.Scene.addObject(meshName, faceObj);
|
||||
renderer.SetObjectMaterial(meshName, materialName);
|
||||
}
|
||||
}
|
||||
|
||||
private Color4 GetFaceColor(Primitive.TextureEntryFace face)
|
||||
{
|
||||
Color4 color;
|
||||
|
||||
if (face.TextureID == UUID.Zero)
|
||||
return face.RGBA;
|
||||
|
||||
if (!m_colors.TryGetValue(face.TextureID, out color))
|
||||
{
|
||||
bool fetched = false;
|
||||
|
||||
// Attempt to fetch the texture metadata
|
||||
UUID metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC);
|
||||
AssetBase metadata = m_scene.AssetService.GetCached(metadataID.ToString());
|
||||
if (metadata != null)
|
||||
{
|
||||
OSDMap map = null;
|
||||
try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { }
|
||||
|
||||
if (map != null)
|
||||
{
|
||||
color = map["X-JPEG2000-RGBA"].AsColor4();
|
||||
fetched = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!fetched)
|
||||
{
|
||||
// Fetch the texture, decode and get the average color,
|
||||
// then save it to a temporary metadata asset
|
||||
AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString());
|
||||
if (textureAsset != null)
|
||||
{
|
||||
int width, height;
|
||||
color = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height);
|
||||
|
||||
OSDMap data = new OSDMap { { "X-JPEG2000-RGBA", OSD.FromColor4(color) } };
|
||||
metadata = new AssetBase
|
||||
{
|
||||
Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)),
|
||||
Description = "Metadata for JPEG2000 texture " + face.TextureID.ToString(),
|
||||
Flags = AssetFlags.Collectable,
|
||||
FullID = metadataID,
|
||||
ID = metadataID.ToString(),
|
||||
Local = true,
|
||||
Temporary = true,
|
||||
Name = String.Empty,
|
||||
Type = (sbyte)AssetType.Unknown
|
||||
};
|
||||
m_scene.AssetService.Store(metadata);
|
||||
}
|
||||
else
|
||||
{
|
||||
color = new Color4(0.5f, 0.5f, 0.5f, 1.0f);
|
||||
}
|
||||
}
|
||||
|
||||
m_colors[face.TextureID] = color;
|
||||
}
|
||||
|
||||
return color * face.RGBA;
|
||||
}
|
||||
|
||||
private string GetOrCreateMaterial(WarpRenderer renderer, Color4 color)
|
||||
{
|
||||
string name = color.ToString();
|
||||
|
||||
warp_Material material = renderer.Scene.material(name);
|
||||
if (material != null)
|
||||
return name;
|
||||
|
||||
renderer.AddMaterial(name, ConvertColor(color));
|
||||
if (color.A < 1f)
|
||||
renderer.Scene.material(name).setTransparency((byte)((1f - color.A) * 255f));
|
||||
return name;
|
||||
}
|
||||
|
||||
public string GetOrCreateMaterial(WarpRenderer renderer, Color4 faceColor, UUID textureID)
|
||||
{
|
||||
string materialName = "Color-" + faceColor.ToString() + "-Texture-" + textureID.ToString();
|
||||
|
||||
if (renderer.Scene.material(materialName) == null)
|
||||
{
|
||||
renderer.AddMaterial(materialName, ConvertColor(faceColor));
|
||||
if (faceColor.A < 1f)
|
||||
{
|
||||
renderer.Scene.material(materialName).setTransparency((byte) ((1f - faceColor.A)*255f));
|
||||
}
|
||||
warp_Texture texture = GetTexture(textureID);
|
||||
if (texture != null)
|
||||
renderer.Scene.material(materialName).setTexture(texture);
|
||||
}
|
||||
|
||||
return materialName;
|
||||
}
|
||||
|
||||
private warp_Texture GetTexture(UUID id)
|
||||
{
|
||||
warp_Texture ret = null;
|
||||
|
||||
byte[] asset = m_scene.AssetService.GetData(id.ToString());
|
||||
|
||||
if (asset != null)
|
||||
{
|
||||
IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>();
|
||||
|
||||
try
|
||||
{
|
||||
using (Bitmap img = (Bitmap)imgDecoder.DecodeToImage(asset))
|
||||
ret = new warp_Texture(img);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
m_log.Warn(string.Format("[WARP 3D IMAGE MODULE]: Failed to decode asset {0}, exception ", id), e);
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
#endregion Rendering Methods
|
||||
|
||||
#region Static Helpers
|
||||
// Note: axis change.
|
||||
private static warp_Vector ConvertVector(float x, float y, float z)
|
||||
{
|
||||
return new warp_Vector(x, z, y);
|
||||
}
|
||||
|
||||
private static warp_Vector ConvertVector(Vector3 vector)
|
||||
{
|
||||
return new warp_Vector(vector.X, vector.Z, vector.Y);
|
||||
}
|
||||
|
||||
private static warp_Quaternion ConvertQuaternion(Quaternion quat)
|
||||
{
|
||||
return new warp_Quaternion(quat.X, quat.Z, quat.Y, -quat.W);
|
||||
}
|
||||
|
||||
private static int ConvertColor(Color4 color)
|
||||
{
|
||||
int c = warp_Color.getColor((byte)(color.R * 255f), (byte)(color.G * 255f), (byte)(color.B * 255f));
|
||||
if (color.A < 1f)
|
||||
c |= (byte)(color.A * 255f) << 24;
|
||||
|
||||
return c;
|
||||
}
|
||||
|
||||
private static Vector3 SurfaceNormal(Vector3 c1, Vector3 c2, Vector3 c3)
|
||||
{
|
||||
Vector3 edge1 = new Vector3(c2.X - c1.X, c2.Y - c1.Y, c2.Z - c1.Z);
|
||||
Vector3 edge2 = new Vector3(c3.X - c1.X, c3.Y - c1.Y, c3.Z - c1.Z);
|
||||
|
||||
Vector3 normal = Vector3.Cross(edge1, edge2);
|
||||
normal.Normalize();
|
||||
|
||||
return normal;
|
||||
}
|
||||
|
||||
public static Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height)
|
||||
{
|
||||
ulong r = 0;
|
||||
ulong g = 0;
|
||||
ulong b = 0;
|
||||
ulong a = 0;
|
||||
|
||||
using (MemoryStream stream = new MemoryStream(j2kData))
|
||||
{
|
||||
try
|
||||
{
|
||||
int pixelBytes;
|
||||
|
||||
using (Bitmap bitmap = (Bitmap)J2kImage.FromStream(stream))
|
||||
{
|
||||
width = bitmap.Width;
|
||||
height = bitmap.Height;
|
||||
|
||||
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
|
||||
pixelBytes = (bitmap.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4;
|
||||
|
||||
// Sum up the individual channels
|
||||
unsafe
|
||||
{
|
||||
if (pixelBytes == 4)
|
||||
{
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
|
||||
|
||||
for (int x = 0; x < width; x++)
|
||||
{
|
||||
b += row[x * pixelBytes + 0];
|
||||
g += row[x * pixelBytes + 1];
|
||||
r += row[x * pixelBytes + 2];
|
||||
a += row[x * pixelBytes + 3];
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
|
||||
|
||||
for (int x = 0; x < width; x++)
|
||||
{
|
||||
b += row[x * pixelBytes + 0];
|
||||
g += row[x * pixelBytes + 1];
|
||||
r += row[x * pixelBytes + 2];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get the averages for each channel
|
||||
const decimal OO_255 = 1m / 255m;
|
||||
decimal totalPixels = (decimal)(width * height);
|
||||
|
||||
decimal rm = ((decimal)r / totalPixels) * OO_255;
|
||||
decimal gm = ((decimal)g / totalPixels) * OO_255;
|
||||
decimal bm = ((decimal)b / totalPixels) * OO_255;
|
||||
decimal am = ((decimal)a / totalPixels) * OO_255;
|
||||
|
||||
if (pixelBytes == 3)
|
||||
am = 1m;
|
||||
|
||||
return new Color4((float)rm, (float)gm, (float)bm, (float)am);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
m_log.WarnFormat(
|
||||
"[WARP 3D IMAGE MODULE]: Error decoding JPEG2000 texture {0} ({1} bytes): {2}",
|
||||
textureID, j2kData.Length, ex.Message);
|
||||
|
||||
width = 0;
|
||||
height = 0;
|
||||
return new Color4(0.5f, 0.5f, 0.5f, 1.0f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion Static Helpers
|
||||
}
|
||||
|
||||
public static class ImageUtils
|
||||
{
|
||||
/// <summary>
|
||||
/// Performs bilinear interpolation between four values
|
||||
/// </summary>
|
||||
/// <param name="v00">First, or top left value</param>
|
||||
/// <param name="v01">Second, or top right value</param>
|
||||
/// <param name="v10">Third, or bottom left value</param>
|
||||
/// <param name="v11">Fourth, or bottom right value</param>
|
||||
/// <param name="xPercent">Interpolation value on the X axis, between 0.0 and 1.0</param>
|
||||
/// <param name="yPercent">Interpolation value on fht Y axis, between 0.0 and 1.0</param>
|
||||
/// <returns>The bilinearly interpolated result</returns>
|
||||
public static float Bilinear(float v00, float v01, float v10, float v11, float xPercent, float yPercent)
|
||||
{
|
||||
return Utils.Lerp(Utils.Lerp(v00, v01, xPercent), Utils.Lerp(v10, v11, xPercent), yPercent);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs a high quality image resize
|
||||
/// </summary>
|
||||
/// <param name="image">Image to resize</param>
|
||||
/// <param name="width">New width</param>
|
||||
/// <param name="height">New height</param>
|
||||
/// <returns>Resized image</returns>
|
||||
public static Bitmap ResizeImage(Image image, int width, int height)
|
||||
{
|
||||
Bitmap result = new Bitmap(width, height);
|
||||
|
||||
using (Graphics graphics = Graphics.FromImage(result))
|
||||
{
|
||||
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
|
||||
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
|
||||
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
|
||||
graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
|
||||
|
||||
graphics.DrawImage(image, 0, 0, result.Width, result.Height);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue