Jump to content

Recommended Posts

Posted

I have been looking to incorporate a minimap into my mod for some time, and have been researching other mods including FTBChunks and Xaero's Minimap, except trying to just copy what they do is turning out incredibly difficult due to the huge amount of features and dependencies they have that I don't need. I've decided it's best to avoid creating a black box section of my codebase I don't understand (and have much more feature control) and just start writing my own minimap.

The naive approach to this is probably:

  1. Look at all the blocks in the vicinity of the player
  2. Get the average texture colour for each block
  3. Do logic related to elevation, water depth, etc. to adjust colour
  4. Blit a rect to the screen of that colour
  5. Repeat for every single block in range

Except of course this sounds incredibly performance taxing considering there could be 1000s of blocks around you and only gets worse when zooming out the map.

What kind of techniques do these mods use to improve performance?

I also don't want to use the vanilla map item renderer so that I can have more granular control over textures like these minimap mods do, though if there are useful techniques or helper functions it has I could use those too.

Posted

Ok so I tried the above, but am finding that drawing 40000 rectangles (100 radius square) every tick is so expensive I effectively can't play the game.

Is there an alternative to this that I can take? eg. somehow building up the image in memory before calling GuiComponent.

Credit to this old post for pointing me to right functions for updateMapColourData. Unfortuantely the post is fairly old and the repo is gone so I can't figure out what that fill function used actually was.

This is my current code:

    private static final Minecraft MC = Minecraft.getInstance();
    public static List<Integer> mapColourData = new ArrayList<>();
    public static final int RADIUS = 100;
    private static final int mapRefreshTicksMax = 100;
    private static int mapRefreshTicksCurrent = 100;

    public static void updateMapColourData()
    {
        if (MC.level == null)
            return;

        long timeBefore = System.currentTimeMillis();

        mapColourData = new ArrayList<>();
        for (int x = (int) MC.player.getX() - RADIUS; x < (int) MC.player.getX() + RADIUS; x++)
        {
            for (int z = (int) MC.player.getZ() - RADIUS; z < (int) MC.player.getZ() + RADIUS; z++) {
                int y = MC.level.getChunkAt(new BlockPos(x,0,z)).getHeight(Heightmap.Types.WORLD_SURFACE, x, z);
                int col = MC.level.getBlockState(new BlockPos(x,y,z)).getMaterial().getColor().col;

                // add 0xFF000000 to include 100% transparency
                mapColourData.add(col + (1677721600));
            }
        }

        System.out.println("updated in: " + (System.currentTimeMillis() - timeBefore) + "ms");
        System.out.println("blocks: " + mapColourData.size());
    }

    public static void renderMap(PoseStack poseStack, int x0, int y0) {
        int index = 0;

        for (int x = x0 - RADIUS; x < x0 + RADIUS; x++) {
            for (int y = y0 - RADIUS; y < y0 + RADIUS; y++) {
                if (index < mapColourData.size()) {
                    GuiComponent.fill(poseStack, x, y, x+1, y+1, mapColourData.get(index));
                    index += 1;
                }
            }
        }
    }

    @SubscribeEvent
    public static void renderOverlay(RenderGameOverlayEvent.Post evt) {
        mapRefreshTicksCurrent -= 1;

        if (mapRefreshTicksCurrent <= 0) {
            mapRefreshTicksCurrent = mapRefreshTicksMax;
            updateMapColourData();
        }
        renderMap(evt.getMatrixStack(), 0,0);
    }

 

Posted (edited)

Hi, I had actually just finish implementing a similar feature, so I find I may be able to help here.
The previous way (calling fill for every pixel) is definitely going to eat up lots of performance, thus it's not an ideal way.

This is what it looks like:

g7a7CbJ.png

 

As always, I'm not able to guarantee the efficiency and if it's the correct way/best practice to do so, so please take this as a reference only.

For how to get map colours check out MapItem#update. The first two for loops are z and x coordinates, and the other two should be x2 and z2 offset coordinates (I think they are used for blending colours around... not really sure and didn't look into it).

 

You will then get a list of integers ("packed id" of material colours), and you are able to create a new DynamicTexture, fill in all the pixels, and register a render type of RenderType.textSeeThrough() with your texture. Then, you can render the map with your renderType along with your positioned texture.

 

    
    static DynamicTexture MAP_TEXTURE;
    static RenderType MAP_RENDER_TYPE;

    public static void run(UpdateScoreboardMapMessage message)
    {
        AVAScoreboardManager manager = AVAWorldData.getInstance().scoreboardManager;
        manager.updateMap(message.compound);
        if (AVARenderer.MAP_TEXTURE != null)
            AVARenderer.MAP_TEXTURE.close();
        AVARenderer.MAP_TEXTURE = new DynamicTexture(manager.getMapWidth(), manager.getMapHeight(), true);
        NativeImage pixels = AVARenderer.MAP_TEXTURE.getPixels();
        if (pixels != null && manager.hasMap())
        {
            for (int y = 0; y < manager.getMapHeight(); y ++)
                for (int x = 0; x < manager.getMapWidth(); x ++)
                    pixels.setPixelRGBA(x, y, MaterialColor.getColorFromPackedId(manager.getMapColours().get(x + y * manager.getMapWidth())));
            AVARenderer.MAP_TEXTURE.upload();
            AVARenderer.MAP_RENDER_TYPE = RenderType.textSeeThrough(Minecraft.getInstance().textureManager.register(AVA.MODID + "_" + "scoreboard_map", AVARenderer.MAP_TEXTURE));
        }
    }

(Maybe it is not the proper way of resource managing??)

 

    private static void renderMap(PoseStack stack, Direction direction, float x, float y, float x2, float y2)
    {
        MultiBufferSource.BufferSource buffer = MultiBufferSource.immediate(Tesselator.getInstance().getBuilder());
        VertexConsumer consumer = buffer.getBuffer(MAP_RENDER_TYPE);
        Matrix4f matrix4f = stack.last().pose();

        putTextureVertex(consumer, matrix4f, x, y, x2, y2, AVAConstants.VANILLA_FULL_PACKED_LIGHT, 0.8F, direction);
        buffer.endBatch();
    }

 

    public static void putTextureVertex(VertexConsumer consumer, Matrix4f matrix4f, float x, float y, float x2, float y2, int light, float alpha, @Nullable Direction direction)
    {
        int a = (int) (alpha * 255.0F);
        consumer.vertex(matrix4f, x, y2, 0.0F).color(255, 255, 255, a).uv(0.0F, 1.0F).uv2(light).endVertex();
        consumer.vertex(matrix4f, x2, y2, 0.0F).color(255, 255, 255, a).uv(1.0F, 1.0F).uv2(light).endVertex();
        consumer.vertex(matrix4f, x2, y, 0.0F).color(255, 255, 255, a).uv(1.0F, 0.0F).uv2(light).endVertex();
        consumer.vertex(matrix4f, x, y, 0.0F).color(255, 255, 255, a).uv(0.0F, 0.0F).uv2(light).endVertex();
    }

 

Hopefully this helps a bit with the direction.

Edited by poopoodice
Posted (edited)

Ok I tried this flow here and its just producing a fully black square on my screen:

The mapRefreshTicksMax timer is just 100ms

updateMapColours() is the same as the function I posted above (producing a 40000-size array of ARGB values) and is correctly producing the data

updateMapTexture() is the same as your run() function except I don't reinitialise MAP_TEXTURE every call (that was causing a crash)

renderMap() is also the same as yours, except I'm not sure what the value of light is supposed to be for putTextureVertex() (I experimented with values ranging 1-255 and found no difference)

Just to be sure its not my data causing the issue I also tried hardcoding pixels.setPixelRGBA(0x7F7F7F7F) which should have at least changed the square to a solid grey but no change.

Ok I think when removed the initialisation of MAP_TEXTURE every tick I also had to remove the MAP_TEXTURE.close(), and that solved it.

Thanks for the reference code, it was really helpful

Edited by SoLegendary
solved it
Posted (edited)

Just noticed some potential problems:
1. You are always using the same instance of DynamicTexture, but closes/dispose it every update.

2. RenderGameOverlayEvent.Post is called multiple times every render tick, it means you are refreshing your map every 1~2 seconds, depend on the render rate.

3. Continue with 2., you are rendering multiple times (it gets called whenever an element is being rendered, e.g. health bar, crosshair, helmet... if you are using 1.16, otherwise you need to register your overlay instead of using the event) every frame, check for ElementType.ALL (or something similar) and do the render.

Edited by poopoodice
Posted

Regarding the map elevation and shading effects that the vanilla map item has using MapItem.update(), how did you apply this same effect to your map? It's not quite as simple as copying the same function as it seems to be designed for use of a MapItemSavedData object as opposed to an ARGB Array. Did you first convert the array to a MapItemSavedData object or did you rewrite the function to work on an ARGB array?

Posted

You are directly using the plain material colour of the block currrently.

If you want anything more

Quote

For how to get map colours check out MapItem#update. The first two for loops are z and x coordinates, and the other two should be x2 and z2 offset coordinates (I think they are used for blending colours around... not really sure and didn't look into it).

 

Posted

Actually if I'm not mistaken, the vanilla map shading just does three things (assuming this map is north facing):

1. if the block directly north is a higher Y, shade it darker

2. if the block directly north is a lower Y, shade it lighter

3. Shade water blocks lighter for shallower, darker for deeper

image.png

Posted (edited)

Ok so it's all working now - just one last thing - How can I rotate the rendered map? I just want it to be rotated 45 degrees so it can be rendered diamond-shaped.

Similarly I want to blit a background for the map (just the map item texture as held in the players' hands) which also needs to be rotated 45 degrees.

EDIT: putting this in a new topic post

 

Edited by SoLegendary
moved to new post

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Im trying to build my mod using shade since i use the luaj library however i keep getting this error Reason: Task ':reobfJar' uses this output of task ':shadowJar' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. So i try adding reobfJar.dependsOn shadowJar  Could not get unknown property 'reobfJar' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler. my gradle file plugins { id 'eclipse' id 'idea' id 'maven-publish' id 'net.minecraftforge.gradle' version '[6.0,6.2)' id 'com.github.johnrengelman.shadow' version '7.1.2' id 'org.spongepowered.mixin' version '0.7.+' } apply plugin: 'net.minecraftforge.gradle' apply plugin: 'org.spongepowered.mixin' apply plugin: 'com.github.johnrengelman.shadow' version = mod_version group = mod_group_id base { archivesName = mod_id } // Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17. java.toolchain.languageVersion = JavaLanguageVersion.of(17) //jarJar.enable() println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" minecraft { mappings channel: mapping_channel, version: mapping_version copyIdeResources = true runs { configureEach { workingDirectory project.file('run') property 'forge.logging.markers', 'REGISTRIES' property 'forge.logging.console.level', 'debug' arg "-mixin.config=derp.mixin.json" mods { "${mod_id}" { source sourceSets.main } } } client { // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. property 'forge.enabledGameTestNamespaces', mod_id } server { property 'forge.enabledGameTestNamespaces', mod_id args '--nogui' } gameTestServer { property 'forge.enabledGameTestNamespaces', mod_id } data { workingDirectory project.file('run-data') args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') } } } sourceSets.main.resources { srcDir 'src/generated/resources' } repositories { flatDir { dirs './libs' } maven { url = "https://jitpack.io" } } configurations { shade implementation.extendsFrom shade } dependencies { minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" implementation 'org.luaj:luaj-jse-3.0.2' implementation fg.deobf("com.github.Virtuoel:Pehkui:${pehkui_version}") annotationProcessor 'org.spongepowered:mixin:0.8.5:processor' minecraftLibrary 'luaj:luaj-jse:3.0.2' shade 'luaj:luaj-jse:3.0.2' } // Example for how to get properties into the manifest for reading at runtime. tasks.named('jar', Jar).configure { manifest { attributes([ 'Specification-Title' : mod_id, 'Specification-Vendor' : mod_authors, 'Specification-Version' : '1', // We are version 1 of ourselves 'Implementation-Title' : project.name, 'Implementation-Version' : project.jar.archiveVersion, 'Implementation-Vendor' : mod_authors, 'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"), "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", "TweakOrder" : 0, "MixinConfigs" : "derp.mixin.json" ]) } rename 'mixin.refmap.json', 'derp.mixin-refmap.json' } shadowJar { archiveClassifier = '' configurations = [project.configurations.shade] finalizedBy 'reobfShadowJar' } assemble.dependsOn shadowJar reobf { re shadowJar {} } publishing { publications { mavenJava(MavenPublication) { artifact jar } } repositories { maven { url "file://${project.projectDir}/mcmodsrepo" } } }  
    • Todas as versões do Minecraft Forge são repentinamente tela preta, mesmo sem mods (tentei reinstalar o Minecraft original, Java, atualizar os drivers não funciona)
    • When i join minecraft all ok, when i join world all working fine, but when i open indentity menu, i get this The game crashed whilst unexpected error Error: java.lang.NullPointerException: Cannot invoke "top.ribs.scguns.common.Gun$Projectile.getDamage()" because "this.projectile" is null crash report here https://paste.ee/p/0vKaf
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.